Skip to content Skip to sidebar Skip to footer

Stop Propagation Not Working For Link Inside Clickable Div

I've got a link that needs to be clicked situated inside a div that already has a function on click which I've emulated here. Now in my code, the link that needs to be clicked has

Solution 1:

Ok, here we go:

$('.search-box').on('click', '.remove-tag', function(event){
    event.stopPropagation();
    $(this).parent().remove();
});

JSFIDDLE: http://jsfiddle.net/snr9D/4/

Since you are adding the element later to the DOM, you need the delegated handler, to bind the event to that.


Solution 2:

The stopImmediatePropagation is working fine, the real problem is because your click event handler is not fired.

Is not fired because you are adding dynamically your elements to the DOM.

In this case you have to use event delegation with jQuery on.

Ref:

The majority of browser events bubble, or propagate, from the deepest, innermost element (the event target) in the document where they occur all the way up to the body and the document element. In Internet Explorer 8 and lower, a few events such as change and submit do not natively bubble but jQuery patches these to bubble and create consistent cross-browser behavior.

If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

Code:

$('.search-box').on('click','.remove-tag',function (event) {
    event.stopImmediatePropagation();
    $(this).parent().remove();
});

Demo: http://jsfiddle.net/M3HdC/


Solution 3:

You are not binding the click event to the .remove-tag elements when they are created.

Just run this in the method where you append the elements to the body:

$('.remove-tag').click(function(event){
    event.stopImmediatePropagation();
    $(this).parent().remove();
});

JSFiddle


Post a Comment for "Stop Propagation Not Working For Link Inside Clickable Div"