Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only parent, exclude everything else while click()

I have a #container and buttons which are children to this container. When I click the container itself (the white space around the buttons), I want it to change its background color but I want nothing to happen when I click the buttons.

Selecting the #container in jquery, though, makes clicking the buttons change the bg as well...

<div id="container">
   <div class="button>
      <span class="text">Button 1</span>
   </div>
   <div class="button>
      <span class="text">Button 2</span>
   </div>
</div>

$("#container").click(function() {
   $('#container').css({background: 'blue'});
});

I've tried many things, nothing seems to be working.

like image 574
dwelle Avatar asked Aug 01 '26 14:08

dwelle


1 Answers

Examine the original target of the event:

$("#container").click(function(event) {
   if(event.target === this) {
       $('#container').css({background: 'blue'});
   }
});

Reference: event.target

like image 190
Felix Kling Avatar answered Aug 07 '26 13:08

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!