Reputation: 1929
I have some jQuery code to close my menu:
$('body').click(function(){
$('#menu').hide();
});
$("#menu").click(function(e) {
e.stopPropagation();
return false;
});
However on my #menu element I have some elements that have click events attached to them:
$('.menu_elem').live("click", function(){
//Do something
});
My problem is that the e.stopPropagation() is preventing my click events for my menu. How can I avoid this?
Upvotes: 2
Views: 150
Reputation: 707158
I'm not sure I understand your HTML exactly, but if #menu
is the root of your menu and .menu_elem
are menu items in the menu, then you could change your delegated event handling to to be captures at #menu
like this:
$("#menu").on("click", ".menu_elem", function () {
// do something
});
This has the following advantages:
It changes the delegated event handling to capture the bubbled events at #menu
so it doesn't need propagation beyond #menu
in order to work so you don't have to change your.stopPropagation()
code.
It switches away from (the now deprecated) .live()
to the replacement .on()
which gives you more control over where the bubbled events are captured.
Upvotes: 1
Reputation: 55740
Write up your code that you want to execute and call it before you call stopPropagation..
$("#menu").click(function(e) {
// Your code here
e.stopPropagation();
return false;
});
Or use the target attribute to contain your click event
Upvotes: 0
Reputation: 148110
You can use e.target to include or exclude the element in condition for stopPropagation,
$("#menu").click(function(e) {
if(e.target.id == "menu")
{
e.stopPropagation();
return false;
}
});
Upvotes: 2