Vera Perrone Vera Perrone - 1 month ago 12
Javascript Question

Simpel image toggle function won't work (no jQuery)

I have been trying to make this simpel image toggle on click function work but I am not sure what is wrong. I have to use querySelector and addEventListener, also jquery is not allowed. Could anyone please help me figure this out?

document.querySelector(".imageClass").addEventListener("click", function () {
var img = this.src;
if(img.src == "/image/location1.png") {
img.src = "/image/location2.png";
} else {
img.src = "/image/location2.png";
}
});

Answer

Getting a property would most likely return an absolute URL, and you really want to make sure you check the attribute, not the property.

Also, you're accesing src twice, first by doing var img = this.src then by doing img.src

And your condition does the same thing in both cases

document.querySelector(".imageClass").addEventListener("click", function () {
    var img = this;
    var src = img.getAttribute('src');

    if( src == "/image/location1.png" ) {
        img.src = "/image/location2.png";
    } else {
        img.src = "/image/location1.png";
    }
});