2

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>

6
  • I don't see anything wrong with the javascript part, just make sure the image url is right (these are all pointing to nowhere) and the element has some minimum width and height. Commented Sep 10, 2017 at 18:35
  • Other than the images not existing on those URL's, it seems to work fine Commented Sep 10, 2017 at 18:36
  • @adeneo don't you need also need a randomName + 1 since the image names start at 1 ? But you are right about the /img urls not working. I tried them too. Commented Sep 10, 2017 at 18:44
  • @82Tuskers - no, the names of the images isn't relevant, just the index in the array Commented Sep 10, 2017 at 18:51
  • I have all the images on a project folder, and not on a URL. I want to get rid of the "url(..." function, but I can't Commented Sep 10, 2017 at 18:56

1 Answer 1

1

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

2 Comments

Thanks Dan! I think that was the problem. Now I'm having trouble figuring out how to generate those images, and since I don't want to use a URL, how to replace the "url" with the path of a project folder?
@Angelina You can use relative urls from the location where your index.html is present.

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.