Reputation: 3582
I've got a close button in a DIV, with both the DIV and the close button also having click()
events attached to them. When I click the close button it also triggers the div click()
event. I know I could put a SPAN inside the div and attach my click event to the span instead of the DIV, but is there a way I can keep both the div click event and the close button click event and not trigger the div click()
when I click the close button?
<div id="sendFeedback" class="feedback with-round-borders with-padding with-box-shadows">Send us your feedback <span id="closeFeedback" class="ui-icon ui-icon-circle-close" style="float:right"></span></div>
<script>
$(document).ready(function() {
$("#sendFeedback").click(function() {
alert('test');
});
$("#closeFeedback").click(function() {
$("#sendFeedback").fadeOut();
})
});
</script>
Upvotes: 2
Views: 2911
Reputation: 4924
$('#closeFeedback').click(function(e){
$('#sendFeedback').fadeOut();
e.stopPropagation();
});
Upvotes: 1
Reputation: 20333
Yep. You should cancel the bubbling of the event up in the DOM tree.
For futher info see the Event#stopPropagation() in the DOM Event documentation.
Upvotes: 2
Reputation: 76003
Add event.stopPropagation()
to the <span>
click event handler:
$(document).ready(function() {
$("#sendFeedback").click(function() {
alert('test');
});
$("#closeFeedback").click(function(event) {
event.stopPropagation();
$("#sendFeedback").fadeOut();
})
});
.stopPropagation()
will stop the event from bubbling up to the div (or any other ancestor): http://api.jquery.com/event.stopPropagation/
Here is your jsfiddle updated: http://jsfiddle.net/jasper/t5VPN/2/
Upvotes: 6