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:

  1. mousedown event triggered, followed mouseup event both on button
  2. click event handler triggered on button
  3. clicked class added .wrap div
  4. click event bound body, delegated elements matching .clicked
  5. event bubbles through dom body
  6. click event handler triggered on body
  7. jquery's click event handler looks elements descendants of current element (the body) match .clicked selector
  8. it finds .wrap div has clicked class , calls event handler on element.

Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -