Reputation: 12177
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 ()
Upvotes: 4
Views: 2349
Reputation: 74738
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>
Upvotes: 5
Reputation: 892
You can check the click target element and not fire toggle if target element is bar. See following code snippet.
$('#foo').click(function (e) {
if(!$(e.target).hasClass("bar")){
$('#foo').find('#bar').toggle('fast');
}
});
You can also see this fiddle.
Upvotes: 2
Reputation: 3841
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();
});
})
Upvotes: 2
Reputation: 19049
One way of doing it: http://jsfiddle.net/4bzvp7o2/2/
$(document).ready(function () {
$('#foo').on('click', function (evt) {
if (evt.originalEvent.target.id === 'bar') {
return false;
}
$('#foo').find('#bar').toggle('fast');
})
})
Upvotes: 0