When designing web application with JavaScript event handling, it is important
to figure out what the (possible) target element is.
Let's take mouseover as example, see the following description from [1]:
mouseover
Fires when the user moves the mouse over the element you registered the
event on or one of its descendants.
There is an example illustrating this situation in [2]. And mouseenter event in
[3] provides a 'do not bubble' version of the mouseover event, but it is a pity
that neither Firefox or Chrome supports the event. So, when you get the event
target element (or srcElement) in the callback function of events, it is
possible the target element may be one of descendant elements. As a result, when
dealing with the callback function of events, REMEMBER to CHECK what the TARGET
ELEMENT is.
I wrote sample code to show how to deal with the target issue of JavaScript
event handling. Please see the following demo and code:
<!doctype html><html><head><metacharset="utf-8"><title>Check Event Target Example</title><linkrel="stylesheet"type="text/css"href="style.css"></head><bodyonload="addevt()"><divid="div1">I am div1. Try to click me.
<br/><br/><divid="div2">I am div2. Try to click me.
<br/><br/><spanid="span1">I am span1. Try to click me.</span></div></div><divid="info"style="margin-top: 20px;width: 30%; margin-left:35%; margin-right:35%;"/><scriptsrc="target.js"></script></body></html>
/* IE: attachEvent, Firefox & Chrome: addEventListener */function_addEventListener(evt,element,fn){if(window.addEventListener){element.addEventListener(evt,fn,false);}else{element.attachEvent('on'+evt,fn);}}function_getParentElement(element,id){/* sometimes mouse event return the child element of actual element we need, so we need to check parent element *//* Chrome and Firefox use parentNode, while Opera uses offsetParent */while(element.parentNode){if(element.id==id){returnelement;}element=element.parentNode;}while(element.offsetParent){if(element.id==id){returnelement;}element=element.offsetParent;}returnnull;}functiononDiv1Click(evt){if(!evt){evt=window.event;}vartarget=evt.target||evt.srcElement;document.getElementById("info").innerHTML=target.id+" clicked";if(target.id!='div1'){varediv1=_getParentElement(target,'div1');document.getElementById("info").innerHTML+='<br />'+ediv1.id+' element was gotten';}}functionaddevt(){_addEventListener('click',document.getElementById("div1"),onDiv1Click);document.getElementById("info").innerHTML="only div1 onclick event registered";}
As you can see, only div1 onclick event is registered. But when child elements
(i.e., div2 or span1) of div1 are clicked, the target element of the
callback function is the child element, not div1. The _getParentElement
function is provided in the sample code to show how to reach div1 in this
case.