0

I want to reuse an image swap function on multiple divs, but the function is not acknowledging the adbox variable on the var rotator = getelementbyid(adbox).

window.onload = animatez(animate);

the animatez function should pass "animate" which is the div id to getelementbyid inside the function.

function animatez(adbox) {
var adbox;
var rotator = document.getElementById(adbox); 
var images = rotator.getElementsByTagName("img");
var counter = 1;
setInterval(function () {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none"; }
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;}
            }, 1000);
};
window.onload = animatez(animate);
<style>
#animate { width:200px; height:200px; background-color:transparent;
margin:auto; position:absolute;
} 

img {width:200px; height:200px; display:none;}
</style>
<body>
<div id="animate">
<img src="surveyfunny.png">
<img src="myanswertoasurveyquestion.png">
<img src="funny-wheredoyoulive.png">
<img src="funnysurveyquestion2.png">
<img src="funnysurveyquestion.png">
</div>

1
  • Why are you re-declaring adbox even if you are passing it as an argument?? Remove var adbox; and try again. Commented Feb 29, 2016 at 19:48

2 Answers 2

1

You need give the function a string parameter. Without quote the animate is undefined, javascript throw the error.

see https://jsfiddle.net/pconline2046/u5cbwpuL/3/#

window.onload = function(){
    animatez('animate');
};
Sign up to request clarification or add additional context in comments.

Comments

1

window.onload needs to be set equal to a function, not the result of calling your animatez function. You could do something like this.

window.onload = function(){
    animatez('animate');
};

Also notice that you need to pass a string to your animatez function so I have quoted animate.

Edit: Like some other answers have stated you also should remove the var adbox; line in your function.

3 Comments

Thanks I fixed the code, still learning javascript, why does the animatez function have to be wrapped inside another function before calling window load?
window.onload allows you to specify a function that will be called when the window is finished loading. It needs to be set equal to a function reference. This can be defined inline like in my example or be a named function like window.onload = myFunction without the parentheses that would call the function immediatelly.
Also you can't define the arguments that are passed to the onload function. This will always be the event object. Wrapping your animatez function inside another function allows passing the argument that you want.

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.