javascript - Event Propagation and Multiple Event Handlers -
okay, i'm confused. i've got global click event handler on document
. on page have few links. each link handled same click event handler that, among other things, prevents event bubbling document level , prevents link executing. of these links, 1 has specific click handler supposed thing , pass off event generic click event links. it's not.
document.onclick = function() { document.body.innerhtml += "you clicked me!"; }; document.getelementsbytagname("a")[0].onclick = function(e) { this.innerhtml += " click it!"; e.stoppropagation(); //this return false appears //prevent link default action return false; }; document.getelementbyid("link").onclick = function(e) { this.innerhtml += " go ahead, "; //but return false appears stop //the propagation previous event //i think removing link below //would cause event propagate event //above stop propagation , //prevent default, apparently //not case; removing line below causes //the link load google normal return false; };
how lower event fire , upper event cancels event?
see mean here
ha, duh. using element.on<event>
setting property in dom element, means each event can have 1 handler. instead, need use addeventlistener
combined proper use of event.preventdefault()
, event.stoppropagation()
in first attempts, putting wanted first handler second, meant overriding first. in case, need put handler want first first, since handler being attached event.
my revised code should be:
document.onclick = function() { document.body.innerhtml += "you clicked me!"; }; document.getelementbyid("link").addeventlistener("click",function() { this.innerhtml += " go ahead, "; }); document.getelementsbytagname("a")[0].addeventlistener("click",function(e) { this.innerhtml += " click it!"; e.stoppropagation(); e.preventdefault(); });
Comments
Post a Comment