Tuesday 23 August 2016

html - Javascript click event handler - how do I get the reference to the clicked item?



My HTML:




This turns green

This turns blue





So first of all, why am I supposed to be passing "event" into the click handler and is event some kind of system keyword?
Also, since the click handler is identified on the container div, how do I know which button has been clicked?


Answer



event is an Event object which is created automatically when an event is fired. Note that you don't have to call it event (I tend to call it simply e). That Event object has a number of properties which describe the event it represents. In this case, the one you're interested in would be target, which shows the element that was the source of the event:



function clickHandler(e) {
var target = e.target;

}


Here's a working example.



Unfortunately, it's never quite that simple. While the specification says it should be event.target, Internet Explorer likes to be different, and chooses to use event.srcElement, so you probably want to put in a check to make sure event.target exists! For example:



function clickHandler(e) {
var target = (e.target) ? e.target : e.srcElement;
}


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...