My HTML:
<div id="x" onclick="clickHandler(event)">
<div id="button1">This turns green</div>
<div id="button2">This turns blue</div>
</div>
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?
eventis an Event object which is created automatically when an event is fired. Note that you don’t have to call itevent(I tend to call it simplye). That Event object has a number of properties which describe the event it represents. In this case, the one you’re interested in would betarget, which shows the element that was the source of the event: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 useevent.srcElement, so you probably want to put in a check to make sureevent.targetexists! For example: