Laura Mentink
Laura Mentink

Reputation: 11

Change an image and change it back with JavaScript click events

I have the following code:

window.onload = function () {
'use strict';

var alcohol = document.getElementById('alcohol'); 

var changeImage = function (event) {
    alcohol.src = "image/alcohol3.jpg";
};

var changeBack = function (event) {
    alcohol.src = "image/alcohol.jpg";
};

addHandler(alcohol, "click", changeImage);
// addHandler(alcohol, "mouseout", changeBack);

How can I change the image back with a second click event? At the moment, it's not working.

Upvotes: 1

Views: 1022

Answers (3)

Deniz Traka
Deniz Traka

Reputation: 84

You can use toggle:

$("#alcohol").toggle(
  changeImage() ,
  changeBack()
);

Upvotes: 0

user1321425
user1321425

Reputation:

You could use a closure like that to do so :

var changeImage = function() {
    function a(event) {
        alcohol.src = "image/alcohol3.jpg";
        event.srcElement.onclick = b;
    }
    function b(event) {
        alcohol.src = "image/alcohol.jpg";
        event.srcElement.onclick = a;
    }
    return a;
}
addHandleaddHandler(alcohol, "click", changeImage());

First it is the a function that is assigned as the handler and each the event is raised the handler is toggled between a and b.

Upvotes: 0

Curtis
Curtis

Reputation: 103388

Change your changeImage function to:

var changeImage = function (event) {
    if (alcohol.src != "image/alcohol3.jpg"){
       alcohol.src = "image/alcohol3.jpg";
    }
    else
    {
       alcohol.src = "image/alcohol.jpg";
    }
};

Upvotes: 1

Related Questions