Sam Beers Sam Beers - 7 months ago 25
Javascript Question

Pass "e" to a new function - javascript

I have a function that waits for a click event on an img and then launches imgclick();

This is all working as expected, but once inside the function i need to use e.preventDefault() which fails because "e" is not available. I thought I could remedy this by just passing in the literal e, but that was no good either. How should I access it properly? Below is my current JS...

var img = document.getElementsByClassName("img"),
i;

function imgclick(id, e) {
e.preventDefault();
e.stopPropagation();
}

for (i = 0; i < img.length; i++) {
img[i].addEventListener("click", imgclick(this.id, e));
}


I'm still getting the hang of not relying on jQuery, so sorry if this is a really obvious mistake.

Answer

First : when adding eventListener, you need reference to the callback function, not to call it.
Second : event, or e argument should be the first argument of the callback function, and having e, you can find e.target.id inside that function:

var img = document.getElementsByClassName("img"),
    i;

function imgclick(e) {
  e.preventDefault();
  e.stopPropagation();
  var id=e.target.id;

}

for (i = 0; i < img.length; i++) {
  img[i].addEventListener("click", imgclick);
}
Comments