I’d like to inject a random background-image into a div. I came across the following code which does this perfectly using the jQuery library:
Sets the array of images:
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];
Sets the div for the random background using previously defined array:
$('#div').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'});
Here’s the thing – I’d like to do this without having to load the jQuery library. I like the simplicity of the above code, but I’m new to the Javascript language and I don’t know to reformat this for use without jQuery.
I’ve spent some time looking for Javascript alternatives to the above code, but they’re all relatively lengthy or unnecessarily “busy”. Any help on this is much appreciated.
This can be done in plain JS easily as well: