J. H.
J. H.

Reputation: 79

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

Upvotes: 1

Views: 88

Answers (3)

mplungjan
mplungjan

Reputation: 177685

Alternative to other answer, if you move the event assignment from inline to the script tag, you can use this - right now your this is window.

If you have more than one image you can give them a class and do

window.onload=function() {
  var imgs = document.querySelectorAll(".labelImage");
  for (var i=0, n=imgs.length;i<n;i++) {
    imgs[i].onclick=function() {
      this.src = this.getAttribute("data-src2"); 
      // or possibly this.src = this.src.replace(/label\./,"label2.")
    }
  }
}

using

<img class="labelImage" src="img/label1.png" data-src2="img/label1x.png" />
<img class="labelImage" src="img/label2.png" data-src2="img/label2x.png" />
<img class="labelImage" src="img/label3.png" data-src2="img/label2x.png" />

Inline, this also works, I however recommend you do not use inline functions:

<img src="img/label.png" onclick="this.src='img/label2.png'" />

Upvotes: 0

user5066707
user5066707

Reputation:

And an alternative of @Justinas answer is to pass this context to this function call, just like my comment said:

changeSource.call(this, "img/label2.png")

Upvotes: 1

Justinas
Justinas

Reputation: 43441

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;
}

Upvotes: 3

Related Questions