0
$().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?

3
  • 2
    because #move-to click is being propagated to body element. It's called event propagation in JS. Commented May 23, 2012 at 15:23
  • 1
    You really shouldn't be binding click events inside of click events (unless your usecase is an edgecase i guess) Commented May 23, 2012 at 15:26
  • 1
    @KevinB: That can be useful for popup menus. Commented May 23, 2012 at 15:37

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0
$().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.

1 Comment

Yes of course. There will be unbind in function. It's only simple variant of function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.