i'm attempting surprisingly difficult task of finding out element clicked. have these functions head first ajax:
function getactivatedobject(e) { var obj; if (!e) { obj = window.event.srcelement; } else if (e.srcelement) { obj = e.srcelement; } else { obj = e.target; } return obj; } function addeventhandler(obj, eventname, handler) { if (document.attachevent) { obj.attachevent("on" + eventname, handler); } else if (document.addeventlistener) { obj.addeventlistener(eventname, handler, false); } }
and code:
mainpane = document.getelementbyid("maindiv"); contactpane = document.getelementbyid("contactdiv"); addeventhandler(mainpane, "click", openfunction); addeventhandler(contactpane, "click", openfunction); function openfunction(e) { var me = getactivatedobject(e); //some other stuff }
unfortunately, me variable refers div, refers image inside div. though image has no onclick function or other kind of event! how can div triggered event?
you're dealing event bubbling.
basically, click on child element bubbles through of child's parents; if parents have click handler bound them, execute.
in pseudocode: can see element current target is, , if it's not div, know need element's parent.
using example, (simplified bit example; in reality, you'd need more robust):
function getactivatedobject(e) { var obj; if (!e) { obj = window.event.srcelement; } else if (e.srcelement) { obj = e.srcelement; } else { obj = e.target; } // images direct children of our div. if our source element img, should // fetch parent if(obj.tagname.tolowercase() === "img"){ obj = obj.parentnode; } return obj; }
note work example only; in real world, need iterate dom tree, comparing parentnodes
elements interested in until you've found you're looking for.
most javascript libraries abstract away (jquery, example, sets currenttarget
property of events dispatches refers element need, encapsulating traversal work you). makes easier, it's not terrible job write , i'd argue against including overhead of entire javascript library if that's need do. :-)
edit: totally destroyed formatting! d'oh!
Comments
Post a Comment