Reputation: 5315
I have a simple code. I want to click on the button and alert its id. The button is contained in a div. Both button and div have a click()
bound to them.
Problem: If I click the button the id of button is alerted and then id of div is also alerted afterwards. I want to prevent the id of div from being alerted.
Code:
<html>
<body>
<style type="text/CSS">
#mydiv{
border: 1px dashed blue;
width: 90px;
height: 50px;
}
</style>
<div id="myDiv">
<input type="button" id="myButton" value="Click Me"></input>
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="code.js"></script>
</body>
</html>
Code.js:
$('#myDiv').click(function(){
alert($('#myDiv').attr('id'));
});
$('#myButton').click(function(){
alert($('#myButton').attr('id'));
});
Upvotes: 0
Views: 61
Reputation: 4482
$('#myButton').click(function(e){ // the extra parameter here is the event object
e.stopPropagation(); // stops event bubbling up
alert($(this).attr('id')); // the this in the current scope is the myButton element so you can just use this.id
});
Upvotes: 1
Reputation: 18873
Use event.stopPropagation() as shown :
$('#myButton').click(function(event){
alert($(this).attr('id'));
event.stopPropagation()
});
Upvotes: 1
Reputation: 133403
You need to use event.stopPropagation()
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Use
$('#myButton').click(function(event) {
event.stopPropagation();
alert(this.id);
});
Upvotes: 6
Reputation: 43156
You can use stopPropagation()
method of the event object to prevent it from bubling upwards.
$('#myButton').click(function(e){
e.stopPropagation();
alert($(this).attr('id'));
});
Upvotes: 2