Reputation: 55
I have a list of addresses on my page. Each time a new address is added, I do an Ajax save and then append the new address to my list of addresses. Each address is in a DIV with a class assigned to it and I have delegated a click handler for that class so that when the address div is clicked, I do something with it. What I want to do is include a link within in each address div that allows me to edit that particular address. The problem is that when the link is clicked and the handler is invoked for the link, I'm also triggering the handler for the div. My question is: how can I handle the "Edit" link click without also triggering the click handler for the div it lives within?
<div id="addrdiv">
<div class="customer-shipping-address">
Name 1
Addr 1
<a href='' class='addredit'>Edit This Address</a>
</div>
<div class="customer-shipping-address">
Name 2
Addr 2
<a href='' class='addredit'>Edit This Address</a>
</div>
</div>
Because addresses are being appended into addrdiv, I have delegated the click handler for each div click and each link click like so:
$("#addrdiv").delegate(".customer-shipping-address", "click", function(e){
// do things here when someone clicks the address block
...
}
$("#addrdiv").delegate(".addredit", "click", function(e){
// do things here when someone clicks the edit link within the block
...
}
When someone clicks the Edit link within each address, I want the link's handler to fire and not the one for the address block as a whole. Is this possible to do? If so, how?
Upvotes: 1
Views: 2147
Reputation: 5199
In the event object there is a property "target", this property is the clicked element in this case, so you can check if event.target == this.
Example using jQuery .is :
$("#addrdiv").delegate(".customer-shipping-address", "click", function(e){
if($(e.target).is(this)) {
//you can do $(e.target).is(".customer-shipping-address") too
console.log("clicked element is .customer-shipping-address");
}
});
Upvotes: 0
Reputation: 14990
stopPropagation() would be a quick way to achieve this, just call it within the .addredit
handler on the event
$("#addrdiv").delegate(".addredit", "click", function (e) {
e.stopPropagation();
alert('edit clicked');
});
here is a fiddle http://fiddle.jshell.net/leighking2/phcjdfzd/
Upvotes: 2
Reputation: 2783
Since I did a fiddle to justify my comment, I though I would post it as an answer.
You need to call the stopPropagation method so the event stops bubbling up through the DOM (fiddle):
$("#addrdiv").delegate(".customer-shipping-address", "click", function(e){
// do things here when someone clicks the address block
...
}
$("#addrdiv").delegate(".addredit", "click", function(e){
// do things here when someone clicks the edit link within the block
e.stopPropagation();
}
Upvotes: 3
Reputation: 2596
you need to attach the event to the link.
$("#addrdiv .customer-shipping-address a").delegate(".addredit", "click", function(e){
}
Upvotes: -2