Maxym Marchenko
Maxym Marchenko

Reputation: 13

JQuery function binded to click event of body node with another click event executed immediately

$().ready(function(){
    $("#move-to").click(function(){
        $("body").bind("click",function(){
            alert("foo");
        });
    }); 
});

Why I see alert("foo") immediately after click on "move-to"?
When I bind "alert" on some div in document evrithing is ok.
Can come somebady help?
What I'm doing wrong?

Upvotes: 0

Views: 886

Answers (2)

thecodeparadox
thecodeparadox

Reputation: 87073

$().ready(function(){
    $("#move-to").click(function(e){
      e.stopPropagation();
      $("body").bind("click",function(){
       alert("foo");
      });      
    }); 
});

But I think you code bind the click event again and again when you click on #move-to, this is not good if you don't unbind that click event somewhere else.

Upvotes: 0

SLaks
SLaks

Reputation: 887225

After your #move-to handler runs, the click event bubbles up to the <body>, firing the handler you just bound.

You can prevent that by calling e.stopPropagation().

Alternatively, you can bind the <body> click event after this event cycle by moving the bind() to a setTimeout call.

Upvotes: 3

Related Questions