Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Load Random Images in Javascript(Chrome Extension)

Hi Everyone ,

I am trying to build a chrome extension that loads random images from a directory through HTML & Javascript. I have a directory called images and I have renamed all the images from 1-30. I am getting a javascript error and I am not able to solve it. I would love if some of you guys help me out. The code is below

var totalCount = 30; function ChangeIt() { var num = Math.ceil( Math.random() * totalCount ); document.getElementById("div1").style.backgroundImage = 'images/'+num+'.jpg'; document.getElementById("div1").style.backgroundSize="100%"; document.getElementById("div1").style.backgroundRepeat="fixed"; } ChangeIt()

The error that I am getting is Uncaught Type Error : Cannot read property style of Null at Line 5. I am not able to get past this error and I would require help from the Treehouse community to help me with this one.

3 Answers

Steven Parker
Steven Parker
243,318 Points

There's no obvious cause of that error in this part of the code.

Check the HTML code and be sure it actually does have an element with the id set to "div1". That's exactly the error I would expect to see if there is not one.

If that's not it, you may need to show the whole project. If you have it in a workspace, just make a snapshot of your workspace and post the link to it here.

My HTML code does not have anything except that it references a JavaScript file.. I will post a snapshot of my files

Steven Parker
Steven Parker
243,318 Points

Your script is specifically referencing an element with id "div1", so that must be present in the HTML to avoid the error.

You are right. However I also tried a different option with my Javascript without referencing any HTML. The code for it is given below

var totalCount = 30; function ChangeIt() { var num = Math.ceil( Math.random() * totalCount ); document.body.background = 'images/'+num+'.jpg'; document.body.style.backgroundRepeat = "no-repeat"; document.body.style.backgroundSize = "100%"; } ChangeIt();

This does not work either. Let me know if anything can be done for this.