Joe W Joe W - 1 month ago 15
Javascript Question

Cannot set property 'src' of null

I am trying to rotate an image using javascript and I was trying some code I found on adobes website that does what I was looking for. When I run it it gives me the error: Uncaught TypeError: Cannot set property 'src' of null

It keeps repeating every 5 second interval which is the amount of time between each image

Here is the javascript:

(function () {
var rotator = document.getElementById('rotator'); // change to match image ID
var imageDir = 'images/'; // change to match images folder
var delayInSeconds = 5; // set number of seconds delay
// list image names
var images = ['image2.jpg', 'image3.jpg', 'image4.jpg', 'image1.jpg'];

// don't change below this line
var num = 0;
var changeImage = function () {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();


and here is the html for the image:

<img src="images/image1.jpg" alt="rotating image" width="400" height="300" id="rotator" />


It shows the image1.jpg, but does not rotate it. Is there something blatantly obvious that I am not seeing? Wouldn't surprise me!

Thanks to anyone that can offer advice.

Answer

When in the head (look at the console):

http://jsfiddle.net/m2wce/

This happens because you are declaring the closure and executing right away. When you execute it in the head, the DOM is not ready and this the img tag does not yet exist.

When in the body, after the referenced img, it works:

http://jsfiddle.net/m2wce/1/

Comments