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: Unca
Your script is loaded before the body of your page, so the rotator
element is not found. Remove the var rotator = ...
line and put it inside the changeImage
function instead:
(function () {
var rotator;
var rotatedImageId = 'rotator'; // change to match your HTML
var imageDir = 'images/';
var delayInSeconds = 5;
// 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 () {
if (!rotator)
rotator = document.getElementById(rotatedImageId);
if (!rotator)
return;
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();
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/
I met this problems too.You can make document.getElementById(rotatedImageId)
before you use that function. Another word,you can define rotator to gobal.
This is how i solved this problem.
You need to place this code after your dom gets ready. i.e inside $(document).ready()
or on window.onload
. as:
window.onload=function(){
(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);
})();
If you place that code inside anynomous function inside head (as you did), then it will not be able to load that image element from Dom because Dom would not be fully loaded at that time.