-4
var keys = document.getElementsByClassName("small_key");

for(i=0; i<keys.length; i++) {
    keys[i].addEventListener("click", keyClick);
}

I have the code above and want to know how to write the function "keyClick" so that I know which one of all the elements that's clicked.

function keyClick(){}

This question is not duiplicated since the other question is for document.getElementById and this for document.getElementsByClass. With the difference, getElementById return one element while getElementsByClass returns one or more. I didn't know if it was the same way when you put more than one element with the same listener...

Viktor Lindblad
  • 100
  • 1
  • 9
  • 1
    Side note: Your code is falling prey to [The Horror of Implicit Globals](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html) *(that's a post on my anemic little blog)*. Be sure to declare your variables (such as `i` above). – T.J. Crowder Apr 27 '17 at 09:45
  • (I'm newbie to javascript) What do you mean? Like this, for(var i=0; i – Viktor Lindblad Apr 27 '17 at 09:48
  • 1
    Yes. Or (with modern JavaScript) you might use `let`, depending. – T.J. Crowder Apr 27 '17 at 10:08

2 Answers2

4

Within keyClick, this will refer to the element on which you hooked the event. (It's also available as currentTarget on the event object keyClick receives.) If you want to know what element was actually clicked (e.g, if it was a descendant element of the .small_key element on which you hooked up the handler), that's target on the event object. If the click was directly on the .small_key element (not a descendant), currentTarget and target will be the same.

Example:

var keys = document.getElementsByClassName("small_key");

for(var i=0; i<keys.length; i++) {
    keys[i].addEventListener("click", keyClick);
}

function keyClick(e) {
  console.log("this.id = " + this.id);
  console.log("e.currentTarget.id = " + e.currentTarget.id);
  console.log("e.target.id = " + e.target.id);
}
<p> Try clicking directly on "bbbb", and also on (span within bbbb)</p>
<div id="a" class="small_key">aaaa</div>
<div id="b" class="small_key">bbbb <span id="b-span">(span within bbbb)</span></div>
<div id="c" class="small_key">cccc</div>
<div id="d" class="small_key">dddd</div>
<div id="e" class="small_key">eeee</div>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
-2

Try the Fiddle

You can use this to refer the current object who is raising the event.

var keys = document.getElementsByClassName("small_key");

for(i=0; i<keys.length; i++) {
    keys[i].addEventListener("click", function(){ var ctrl = this; keyClick(this); });
}

function keyClick(obj){
    console.log(obj);
}

Hope this works for you.

Mayank
  • 1,351
  • 5
  • 23
  • 42
  • Why down votes ? It is returning the required DOM element on click event. Add appropriate comments if downvoting. – Mayank Apr 28 '17 at 03:26