ρss
ρss

Reputation: 5315

Regarding click() in jquery

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

Answers (4)

Mardoxx
Mardoxx

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

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

Use event.stopPropagation() as shown :

$('#myButton').click(function(event){
    alert($(this).attr('id'));
    event.stopPropagation()
});

Upvotes: 1

Satpal
Satpal

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);
});

DEMO

Upvotes: 6

T J
T J

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

Related Questions