Angelina
Angelina

Reputation: 31

How do I generate a random image from a JavaScript array of variables into my HTML document?

This is what I have so far in my HTML and JavaScript pages, although I do not want to use a URL in the JavaScript file, since I have the images in my project folder. But when I open the html, no images pop up. I also do not want a background image.

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://angelinawong.com/" + randomName + "')";
<!DOCTYPE html>
<html>
<head><title>47</title></head>
<body>
    <div id="randomImage"/>
    
    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    <script src="popup.js"></script>
</body>
</html>

Upvotes: 2

Views: 289

Answers (1)

Dan Philip Bejoy
Dan Philip Bejoy

Reputation: 4381

Try placing the script tags after the body tag, It could be a problem with the order HTML and JS are loaded.

<!DOCTYPE html>
<html>
<head><title>47</title></head>
<body>
 <div id="randomImage"/>
</body>    
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script src="popup.js"></script>
</html>

Upvotes: 1

Related Questions