simulating onclick event with javascript

Use the fork Luke picture Use the fork Luke · May 31, 2012 · Viewed 8.6k times · Source

What i am trying to do is to put an imagebutton in div which is wider than the button itself and when the outside div is clicked, i want the image button onclick() function to be called. What i expect from below html code is, when i click the button itself, it should alert only "button clicked". when i click the outside div, it should alert "div clicked" first, then "button clicked". The problem is, when i click the div, it alerts: "div clicked" then "button clicked" and then "div clicked" again, in order. When i click the button, it alerts: "button clicked" then "div clicked" then "button clicked" and then "div clicked".

I could not find what i am missing here, any helps?

<html>
<body>
    <div style="width: 200px; border: 1px solid red;" onclick="alert('div clicked');(document.getElementById('addButton')).click();">
        <input type="button" onclick="alert('button clicked');"
            id="addButton"/>
    </div>
</body>
</html>

Answer

Rafael picture Rafael · May 31, 2012

What you've missed is the fact that some events bubble up the document tree triggering all click handlers of parent elements. To stop it, call stopPropagation on the event object.

<input type="button" onclick="event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true);alert('button clicked');"
        id="addButton"/>

(in old IE there is no stopPropagation, you need to set event.cancelBubble=true)