0

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?

Hasib Tarafder
  • 5,773
  • 3
  • 30
  • 44
Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150

6 Answers6

3

Try with the event.stopPropagation() mehtod.

Example here

$(".Buttonclass").live("click",function(event){
    event.stopPropagation();
buttonclick();
});
Gaucho_9
  • 265
  • 1
  • 3
  • 11
3

You have to use event.stopPropagation: DEMO jsFiddle

$(".Buttonclass").live("click",function(e){
buttonclick();
    e.stopPropagation();
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
jacquard
  • 1,307
  • 1
  • 11
  • 16
  • This is similar answer as others already posted and btw here `e` is undefined. Here, you are stopping propagation because of an unhandled js error – A. Wolff Feb 06 '14 at 11:03
  • @A.Wolff Sorry for the error, but that was a honest attempt from me. Will edit the code snippet – jacquard Feb 06 '14 at 11:06
2

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()
};

working Fiddle

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
2

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

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.

Community
  • 1
  • 1
markusthoemmes
  • 3,080
  • 14
  • 23
1
$("#Maindiv").live("click",function(){
    divclick();
});

function divclick(){
    alert("div");
};
$(".Buttonclass").live("click",function(event){
    event.preventDefault();
    event.stopPropagation();
    buttonclick();
});
function buttonclick(){
    alert("button");
};

http://jsfiddle.net/afFLB/6/

This is what you want. Stop Propagation.

Igor Quirino
  • 1,187
  • 13
  • 28