007mrviper 007mrviper - 5 months ago 8
HTML Question

Image swapping using JavaScript not working

I want to swap images using

JavaScript
. When only
section1
is used the swapping of image works but when
section2
is added then the swapping of image works only on
section2
(stops swapping in
section1
).
Codes are:

JavaScript

--section1--


var imagetracker="m";
function change(){
var image=document.getElementById('image1');
if(imagetracker=="m"){
image.src="images/momo 2.jpg";
imagetracker="t";
}else if(imagetracker=='t'){
image.src="images/taco.jpg";
imagetracker="m";
}
}
var timer = setInterval('change()',2000);


--section2--


var imagetracker="p2";
function change2(){
var image=document.getElementById('image2');
if(imagetracker=="p2"){
image.src="images/pizza 2.jpg";
imagetracker="b";
}else if(imagetracker=='b'){
image.src="images/burrito 2.jpg";
imagetracker="p2";
}
}
var timer2 = setInterval('change2()',2000);


HTML

<img src="images/momo 2.jpg" height="150" width="220" id="image1">
<img src="images/pizza 2.jpg" height="150" width="220" id="image2"><p>


How should be done to make
section1
work?

Answer

You have two imagetracker variables. Rename either one so that there is one of each.

You assign imagetracker to "m" and "p2" which will cause an error because there are two defined variables of the same name.

You can change the setInterval lines to:

var timer = setInterval(change, 2000);

This gives the function as a parameter and sets the interval to run change() every 2 seconds. This also applies to the second timer.

Your version is fine and strings are fine to be passed as functions.

Here is a reference on the setInterval function from W3Schools