J. H. J. H. - 16 days ago 5
HTML Question

JS function in <img>-tag doesn't get called

No matter where I put this, it won't work.
Meaning, it won't work inside the html file, in script-tags, not above the hideShow function not below it.
I have one JS file and a html file.
There are two functions in that JS file, the first one works fine, but when I try to call the second one, it just won't work, wheras when I try to execute the same piece of code directly inside the onclick="" property of the img it works.
Here is said JS file:

function hideShow(x,y) {
var hide = document.getElementById(x);
var show = document.getElementById(y);
if (!hide.classList.contains("height-zero") && show.classList.contains("height-zero")) {
hide.classList.add("height-zero");
show.classList.remove("height-zero");
} else {
hide.classList.remove("height-zero");
show.classList.add("height-zero");
}
}

function changeSource(x) {
this.src = x;
}


And this is how I put it in the img-tag

<img src="img/label.png" onClick="changeSource('img/label2.png')">


Note I have more than one image

Answer

You need to pass this to your function:

<img src="img/label.png" onClick="changeSource(this, 'img/label2.png')">

function changeSource(el, x) {
    el.src = x;
}
Comments