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 ()
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>
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();
});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With