Search code examples
javascriptjqueryclicklivepreventdefault

jQuery Prevent div's click behavior when inline href is clicked


I have a div containing a href. The div has a jQuery live click event:

$(".item").live("click", function() { 
    window.location = this.id;  
});

In the div I have a href:

<div class="item" id="/test.html">
    <a href="javascript:void(0);" class="test" id="123">link</a>
</div>

Also with a live click event:

$(".test").live("click", function() { 
    $(".item").unbind('click');
    alert(this.id);
});

What I try to achieve is click the div loads the div id as location while clicking the link inside the div does it's own thing while preventing the div click behavior.

I know I could take the href out of the div but I don's want that ;-)


Solution

  • UPDATED

    If you can, use jQuery 1.7 to do the event delegation using .on and stop the anchor clicks from propagating:

    $(document).on("click","a.test", function(e) { 
        e.stopImmediatePropagation();
    });
    
    $(document).on("click","div.item", function(e) { 
        // whatever
    });
    

    http://jsfiddle.net/AuHjA/3/

    Otherwise use .delegate instead of .live:

    $(document).delegate("a.test", "click", function(e) { 
        e.stopPropagation();
    });
    
    $(document).delegate("div.item", "click", function(e) { 
        //whatever
    });
    

    http://jsfiddle.net/mblase75/AuHjA/4/