Reputation:
I would like to know how do I make the image change to another one, then change back to normal, because the following code doesn't work:
function change(){
img = document.getElementById("img")
img.src = "Login_img2.jpg"
img.onclick = "change2()"
}
function change2(){
img = document.getElementById("img")
img.src = "login_img3.jpg"
img.onclick = "changeN()"
}
function changeN(){
img = document.getElementById("img")
img.src = "login_img1.jpg"
img.onclick = "change()"
}
Upvotes: 1
Views: 2828
Reputation:
You can checkout the fiddle http://jsfiddle.net/7pKxb/ which might give you some ideas.
I'd prefer using flag then swapping between them on click
if (blFlag) {
blFlag = false;
oTux.setAttribute('src', 'http://tux.crystalxp.net/png/brightknight-tux-hatches-3796.png');
} else {
blFlag = true;
oTux.setAttribute('src', 'http://mascot.crystalxp.net/png/pit-tux-sonic-4206.png');
}
Upvotes: 0
Reputation: 74076
A completely different approach: Just hold all image-sources in an array and a variable to show, which image is currently shown. Then you just have to cycle through this array, without having to change the clickhandler every time.
(function(){
// list of images
var images = [ "login_img1.jpg", "login_img2.jpg", "login_img3.jpg" ],
// current shown image
curImage = 0;
// event handler
document.getElementById( 'img' ).addEventListener( 'click', function(){
// get next image in line
curImage = (curImage + 1) % images.length;
// assign it
this.src = images[curImage];
});
})();
Upvotes: 3
Reputation: 104785
You're onclick
functions are being invoked immediately since you're including ()
after the function (also, dont quote them!). Try changing to something like this:
function change(){
img = document.getElementById("img")
img.src = "Login_img2.jpg"
img.onclick = change2;
}
Upvotes: 4