Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  20] [ 2]  / answers: 1 / hits: 36076  / 11 Years ago, fri, june 21, 2013, 12:00:00

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.


More From » javascript

 Answers
6

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 (in other words, the HTML below still hasn't been mounted by the browser, as it processes the page sequencially, from top to botto) and at the time of the execution the img tag does not yet exist (because it is down below in the HTML page).



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



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


[#77494] Thursday, June 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anders

Total Points: 295
Total Questions: 106
Total Answers: 104

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;