Reputation: 7289
Below is my code
Here is the fiddle link
$("#Maindiv:not('.Buttonclass')").live("click",function(){
divclick();
});
function divclick(){
alert("div");
};
$(".Buttonclass").live("click",function(){
buttonclick();
});
function buttonclick(){
alert("button");
};
When i click on the button both "div" click and button click are getting called, i want only button to be called and not the div click function. What am i missing in the not selector?
Upvotes: 0
Views: 54
Reputation: 1307
You have to use event.stopPropagation
: DEMO jsFiddle
$(".Buttonclass").live("click",function(e){
buttonclick();
e.stopPropagation();
});
Upvotes: 3
Reputation: 1195
$("#Maindiv").live("click",function(){
divclick();
});
function divclick(){
alert("div");
};
$(".Buttonclass").live("click",function(event){
event.preventDefault();
event.stopPropagation();
buttonclick();
});
function buttonclick(){
alert("button");
};
This is what you want. Stop Propagation.
Upvotes: 1
Reputation: 388316
First prefer on() instead of live() as it is already deprecated and removed in jquery 1.9
$(document).on("click", "#Maindiv", function (e) {
divclick();
});
$(document).on("click", '#Maindiv .Buttonclass', function (e) {
e.stopPropagation()
});
Demo: Fiddle
Upvotes: 2
Reputation: 3120
You don't need the :not
selector here. You're problem is event bubbling related. A click event will bubble up to the document root, so when you click on a button inside a div, the button will get clicked first, then the event will bubble up to its parent element (the div in this case) and so on.
You can explicitly prevent this behavious by calling event.stopPropagation();
.This will stop the event from bubbling up further at the moment as it is called.
See the fixed http://jsfiddle.net/afFLB/5/
$(".Buttonclass").live("click",function(e){
buttonclick();
e.stopPropagation();
});
Read this one for further information about bubbling.
Upvotes: 1
Reputation: 265
Try with the event.stopPropagation()
mehtod.
$(".Buttonclass").live("click",function(event){
event.stopPropagation();
buttonclick();
});
Upvotes: 3
Reputation: 82231
You need to use event.stopPropagation()
for child button to prevent event getting propogated from parent click event.
function buttonclick(event){
alert("button");
event.stopPropagation()
};
Upvotes: 2