javascript - jQuery event listener fires before selector applied? -
i'm stuck on event listeners. when 1 element clicked want create listener clicks. reason both firing. here's code , jsbin: http://jsbin.com/uhiyigi/2/edit html
<div class="wrap"> <button>click me</button> </div>
js
$('button').on('click', function(event){ $('body').append('<p>button clicked</p>'); $('.wrap').addclass('clicked'); $('body').on('click', '.clicked', function(e){ $('body').append('<p>.clicked clicked</p>'); $('.wrap').removeclass('clicked'); $('body').off('click', '.clicked'); }); });
from understand event listeners, second 1 should not fire until '.clicked' element has complete click event (a mouse down , mouse up), fires on first click, meaning event fired though element doesn't have trigger class until after event. i'm seeing event listener removed each time, it's called before think should called. so, i'm confused now... suggestions? i'm hoping have face palm in near future.
events bubble. when click on button, you're adding event body. once event handler button complete (meaning, wrap has clicked class), continues bubble dom until reaches body. since body has new click event, said event gets triggered. jquery looks within body element matching .clicked
selector, calling handler on finds. stop this, can either delay binding event body settimeout, or stop propagation on button's click event won't bubble body.
$('button').on('click', function(event){ event.stoppropagation(); ...
timeline:
- mousedown event triggered, followed mouseup event both on button
- click event handler triggered on button
clicked
class added.wrap
div- click event bound body, delegated elements matching
.clicked
- event bubbles through dom body
- click event handler triggered on body
- jquery's click event handler looks elements descendants of current element (the body) match
.clicked
selector - it finds
.wrap
div hasclicked
class , calls event handler on element.
Comments
Post a Comment