daisy
daisy

Reputation: 23541

Child click event affecting parent event

I have a HTML structure like this:

<table>
    <tr onclick="alert ('parent event')">
        <td>
             <input type="button" name="click me" value="I'm a button" id="click me" />
        </td>
    </tr>
</table>

Now I have a click event bound on the tr, now if I click on the button, that click event on the tr is also triggered.

How can I stop that from happening?

Upvotes: 0

Views: 393

Answers (4)

Deepak Ingole
Deepak Ingole

Reputation: 15752

In bubbling the event is first captured and handled by the inner most element and then propagated to outer elements.

You should stop event from getting bubbled,

<table>
    <tr onclick="alert('parent click')">
        <td>
            <input onclick="event.stopPropagation();" type="button" name="click me" value="I'm a button" id="click me" />
        </td>
    </tr>
</table>

Fiddle

Upvotes: 0

Alien
Alien

Reputation: 3678

you can solve like below;

html:

<table>
    <tr onclick="trAlert()" bgcolor="#cccccc" width="300" height="300">
        <td>
             <input type="button" onclick="btnAlert()" name="click me" value="I'm a button" id="click me" />
        </td>
    </tr>
</table>

js

function trAlert()
{
    alert('tr');
}

function btnAlert()
{
    event.stopPropagation();
    alert('btn');   
}

see the demo here --->http://jsfiddle.net/Junkie/kZ6J6/

Upvotes: 1

Samuel Liew
Samuel Liew

Reputation: 79073

Change your input ID to click-me (without spaces), then put this between script tags:

window.onload = function() {
    document.getElementById('click-me').onclick = function(e) {
        e.stopPropagation();
        return false;
    }
}

or you can simply put this code in the onclick attribute:

<input type="button" onclick="event.stopPropagation();" ...

http://jsfiddle.net/qwk38/

Upvotes: 2

Faris Nasution
Faris Nasution

Reputation: 3620

Add an onclick handler too to the input, on which the callback contains event.stopPropagation()

function(event) {
  event.stopPropagation();
}

Upvotes: -1

Related Questions