JSFiddle - React, Tailwind, and code Playground

by David Thomas

HTML

<span id="subtitleElementID"></span>

CSS

#subtitleElementID {
    display: inline-block;
    font-weight: bold;
    color: #000;
    background-color: rgba(255,255,255,0.7);
    border-radius: 1em;
    padding: 0.5em;
}

JavaScript

var images = [
    {
        subtitle : 'Subtitle text for image one...',
        src : 'http://placekitten.com/1000/1000'
    },
    {
        subtitle : 'Subtitle text for image two...',
        src : 'http://lorempixel.com/1000/1000/people/'
    },
    {
        subtitle : 'Subtitle text for image three...',
        src : 'http://lorempixel.com/1000/1000/nightlife/'
    },
    {
        subtitle : 'Subtitle text for image four...',
        src : 'http://lorempixel.com/1000/1000/nature/'
    }
];

function setBackground (images) {
    // generates a random integer between 0 and the length of the supplied array:
    var n = Math.floor(Math.random() * images.length),
        // works out whether to use the 'textContent' or 'innerText' property:
        textProperty = 'textContent' in document ? 'textContent' : 'innerText';

    // sets the background-image of the 'body' element:
    document.body.style.backgroundImage = 'url(' + images[n].src + ')';

    // sets the text of the relevant subtitle element:
    document.getElementById('subtitleElementID')[textProperty] = images[n].subtitle;
}

setBackground(images);