Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude an element from jquery .click()

Tags:

jquery

I've got something like this http://jsfiddle.net/4bzvp7o2/ and I want to exclude the #bar element from participating in the toggle function when clicked.

So if one clicks on the blue part when it is visible, nothing will happen, I have tried...

$('#foo').not('#bar').click(function ()
like image 613
Joff Avatar asked Jan 08 '23 09:01

Joff


2 Answers

See your case is very useful to know about event bubbling. When you have an event which is bound on parent element which in your case is $('#foo') to do something when clicked and sometimes people need to do something else to do on child elements when clicked which in your case is $('#bar').

When you click an element which is deep down in the DOM heirarchy then the event happend on it will traverse up to all the parent nodes.

You need to have event.stopPropagation() to stop the event bubbling to the parent node:

$(document).ready(function() {
  $('#foo').click(function() {
    $('#bar').toggle('fast')
  });
  $('#bar').click(function(e) {
    e.stopPropagation(); // stops the event to bubble up to the parent element.
  });
})
#foo {
  width: 100px;
  height: 100px;
  background-color: yellow;
}
#bar {
  width: 50px;
  height: 50px;
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='foo'>
  <div id='bar'>
  </div>
</div>
like image 151
Jai Avatar answered Feb 05 '23 00:02

Jai


Codepen http://codepen.io/noobskie/pen/jbLerX

You need to use e.stopPropagation();

$(document).ready(function() {
  $('#foo').click(function() {
    $('#foo').find('#bar').toggle('fast')
  })
  $('#bar').click(function(e) {
    e.stopPropagation();
  });
})
like image 20
NooBskie Avatar answered Feb 04 '23 23:02

NooBskie