Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent "bubbling"? [duplicate]

I am not sure this is really bubbling, I will explain.

I have this:

<div>
  <div>
    text here
  </div>
</div>

How to bind an on click event so that it will affect only the enclosed div? If I set it like this:

jQuery('div').bind('click', function() {
  jQuery(this).css('background','blue');
});

it makes blue all the divs. If I add false as the third argument(prevent bubbling) to the bind function it does nothing.

How can I solved this?

like image 231
Andrew Avatar asked Dec 12 '22 10:12

Andrew


2 Answers

http://api.jquery.com/event.stopPropagation/

Add event.stopPropagation(); inside the hander.

(It might be better, though, to assign an ID or class to the nested DIV so you can be sure it's the only one affected.)

like image 94
Blazemonger Avatar answered Dec 15 '22 00:12

Blazemonger


You should really use identifiers like IDs or classes, but for your example, you could do this:

jQuery('div > div').bind('click', function() {
  jQuery(this).css('background','blue');
});

...which will bind the handler to any div that is a direct descendant of another div.

So either make your initial selection specific to the element(s) you want to affect, or use event delegation, placing a handler on an ancestor, and testing for the element you want.

Delegation example: http://jsbin.com/ehemac/edit#javascript,live

<div id="container">
    <div class="outer">
      <div>
        text here
      </div>
    </div>
    <div class="outer">
      <div>
        text here
      </div>
    </div>
</div>
jQuery('#container').delegate( '.outer > div', 'click', function() {
    jQuery(this).css('background','blue');
});

This uses the delegate()[docs] method that places a handler on the ancestor with the ID #container.

The first argument to .delegate() is a selector. Any elements that are clicked inside #container will have that selector compared against the element clicked. If the selector matches, the handler will be invoked.

like image 28
user113716 Avatar answered Dec 15 '22 00:12

user113716