Display Title, URL and Image on Refresh

81 views Asked by At

I'm borrowing the solution from Robert (https://stackoverflow.com/users/1200182/robert-messerle) on this question. How to display random parts of a page on refresh?

However, I'd like to also add an image to each of the element lists. How can the solution be updated to do so?

JS

$(function () {
    var data = [
        {
            h1: 'Test Title 1',
            p: 'Test Paragraph 1',
            a: { href: '#test-link1', text: 'Test Link 1' }
        },
        {
            h1: 'Test Title 2',
            p: 'Test Paragraph 2',
            a: { href: '#test-link2', text: 'Test Link 2' }
        },
        {
            h1: 'Test Title 3',
            p: 'Test Paragraph 3',
            a: { href: '#test-link3', text: 'Test Link 3' }
        }
    ];
    //-- select an item at random
    var index = Math.floor( Math.random() * data.length );
    var item  = data[index];
    //-- create the HTML elements
    var $placeholder = $('#placeholder');
    $('<h1>').text(item.h1).insertAfter($placeholder);
    $('<p>').text(item.p).insertAfter($placeholder);
    $('<a>').attr('href', item.a.href).text(item.a.text).insertAfter($placeholder);
});

HTML"

<div id="placeholder"></div>

1

There are 1 answers

0
3h54n75 On

u can edit each data element like this:

{
    h1: 'Test Title 3',
    p: 'Test Paragraph 3',
    a: { href: '#test-link3', text: 'Test Link 3' },
    img: { src: '/1.jpg' }
}

then use this at end of ur js code:

  $('<img>').attr('src', item.img.src).insertAfter($placeholder);