Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  85] [ 6]  / answers: 1 / hits: 5445  / 11 Years ago, wed, december 18, 2013, 12:00:00

I think I must be missing something very obvious. Using this code I want to count up and trigger a background change on a timer; however it doesn't pass the variable, each time the timer calls the function it is passing a undefined variable.



Worth noting:




  • Looked at the consol - no errors

  • I know Jquery would arguably be better but the site can't have jquery due to some nasty legacy issues (thats a whole other question)



The Code



<script>
/* Get the body element */
var body = document.getElementsByTagName('body')[0];
/* Call the function */
changebackground();
/* Set the starting count */
var changecount = 1;
/* Change function */
function changebackground(changecount) {
if(changecount=1){
body.style.backgroundImage = 'url(/templates/images/background_1.jpg)';
changecount = 2;
}
else if (changecount=2) {
body.style.backgroundImage = 'url(/templates/images/background_2.jpg)';
changecount = 3;
}
else {
body.style.backgroundImage = 'url(/templates/images/background_3.jpg)';
changecount = 1;
}
setInterval(function(changecount){changebackground();},3000);
}
</script>

More From » function

 Answers
2

Remove changecount as a parameter to changebackground(). You have it as a global variable so no need to list it in the parameter list.



function changebackground() {
...
}


Then change your setInterval call to:



setInterval(changebackground, 3000);


And also move the call outside of changebackground(). You only need to call setInverval() once, not every time changebackground() is invoked.



Finally, use == for comparisons, not =.



if (changecount == 1) {
body.style.backgroundImage = 'url(/templates/images/background_1.jpg)';
changecount = 2;
}
else if (changecount == 2) {
body.style.backgroundImage = 'url(/templates/images/background_2.jpg)';
changecount = 3;
}
else {
body.style.backgroundImage = 'url(/templates/images/background_3.jpg)';
changecount = 1;
}

[#49411] Tuesday, December 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
amari

Total Points: 736
Total Questions: 111
Total Answers: 90

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;