2

If two onclick are on top of each other, i would like to know how to stop the second one from launching.

Example :

<div id="div1" onclick="alert('a');">
a
<div id="div2" onclick="alert('b');">
b
</div>
a
</div>

if click on div2, i would like to have only alert(b), but NOT alert(a) afterwards.

FIDDLE : https://jsfiddle.net/ae9av150/2/

bob dylan
  • 989
  • 2
  • 10
  • 26

3 Answers3

10
<div id="div1" onclick="alert('a');">
a
<div id="div2" onclick="alert('b');event.stopPropagation();">
b
</div>
a
</div>
Avinash
  • 812
  • 8
  • 17
1
<div id="div1" onclick="alert('a');">
a
<div id="div2" onclick="event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true);alert('b');">
b
</div>
a
</div>

Reference: http://javascript.info/tutorial/bubbling-and-capturing for IE<9, you should use event.cancelBubble=true

Jimish Gamit
  • 1,014
  • 5
  • 15
0

Do like this.

window.onload = function() {
        document.getElementById("div2").onclick = function(e){
          e.stopPropagation();
          alert('b');
        }

    }

HTML

<div id="div1" onclick="alert('a');">
        a
        <div id="div2">
            b
        </div>
        a
    </div>
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53