Reputation: 6190
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 class remove-tag
which is injected on running the script to the outer element search-box
.
Referencing the earlier SO question of:
I applied similar logic to my code here:
$('.remove-tag').click(function(event){
event.stopImmediatePropagation();
$(this).parent().remove();
});
I also tried event.stopPropagation();
, but this doesn't work and clicking on the link still performs the function of the outer div which is technically a drop down sort of system.
Upvotes: 2
Views: 4929
Reputation: 30993
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/
Upvotes: 1
Reputation: 25392
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();
});
Upvotes: 1
Reputation: 1547
Ok, here we go:
$('.search-box').on('click', '.remove-tag', function(event){
event.stopPropagation();
$(this).parent().remove();
});
Since you are adding the element later to the DOM, you need the delegated handler, to bind the event to that.
Upvotes: 3