1

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>

1

1 Answer 1

2

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 + "')"
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Amit! And also can the images be from a folder of images in the project, instead of the "url('bukk.it"? How can I get rid of this part and still make the images work?
You can use "url('./path/to/image/'... And read more about HTML File Paths.
And is it possible to do this with local folders within the project?
I am still a bit confused. This is for a Chrome extension I'm building where images from a folder are generated every time the extension is clicked, but nothing shows up except an empty box
Yes. And again, read about HTML File Paths: w3schools.com/html/html_filepaths.asp The answers to your questions are there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.