user198729
user198729

Reputation: 63686

How to stop event propagating?

<script type="text/javascript">
$(function(){
    $('<h2>Click</h2>').prependTo($('#container')).live('click',function() {
        return false;
    });
    $('#container').click(function() {
        alert(1);
    });
});
</script>


<div id="container">

</div>

I don't want the click event to propagate to the #container,and that's why there is return false,but obviously it's not working

Upvotes: 3

Views: 1238

Answers (4)

K Prime
K Prime

Reputation: 5849

You don't need live for what you're doing - use bind (or click directly) instead:

$('<h2>Click</h2>').prependTo($('#container')).click (function() {
    return false;
});

If you really meant a live-binding to h2s, you should call:

$('h2').live ('click', function () { ... });

Upvotes: 1

jrharshath
jrharshath

Reputation: 26583

live cannot be used to a jquery object like this.

Quoting from Events/live:

Live events currently only work when used against a selector. For example, this would work: $("li a").live(...) but this would not: $("a", someElement).live(...) and neither would this: $("a").parent().live(...).

Upvotes: 0

Doug Neiner
Doug Neiner

Reputation: 66221

It has to do with using the live selector and event delegation. You don't even need that live handler. Change your #container click like this:

$('<h2>Click</h2>').prependTo($('#container'));
$("#container").click(function(e){
    if(e.target.nodeName != "H2"){
       alert(1);
    }
});

Or if it looks nicer to use all jQuery:

$("#container").click(function(e){
    if($(e.target).is('h2') == false){
       alert(1);
    }
});

Both of those examples test where the original click happened, and won't execute if a H2 was clicked.

Upvotes: 3

Tom Bartel
Tom Bartel

Reputation: 2258

Use a parameter to your event handler. That parameter will be bound to the event object:

$('<h2>Click</h2>').prependTo($('#container')).live('click',function(e) {
    e.stopPropagation();
    return false;
});

Upvotes: 0

Related Questions