Angelina
Angelina

Reputation: 31

How do I load a random image from an array in a JavaScript file into HTML every time the page refreshes?

This is what I have so far. But when I run it, an error states that '$' was used before it was defined. Also, no images appear on screen. And I do no want to have the 'url(http://bukk.it/', since I have all the images in the project folder.

var images = ["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg", "img/5.jpg", "img/6.jpg"];


$('#randomImage').css({'background-image': 'url(http://bukk.it/' + images[Math.floor(Math.random() * images.length)] + ')'});
<!DOCTYPE html>
<html>
<head><title>47</title></head>
<body>
    <div id="randomImage"/>
    
    <script type="text/js" src="popup.js"></script>
</body>
</html>

Upvotes: 1

Views: 1847

Answers (1)

Amit Sheen
Amit Sheen

Reputation: 249

Your jQuery is not defined, but you don't have to use it. This will work:

var images = ["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg", "img/5.jpg", "img/6.jpg"];

var randomName = images[Math.floor(Math.random() * images.length)];

document.getElementById("randomImage").style.backgroundImage = "url('http://bukk.it/" + randomName + "')"

Upvotes: 2

Related Questions