Discard a function in JavaScript?

When I press mainDiv, the mainDiv() function is mainDiv() , when I press subDiv, the mainDiv() and subDiv() functions are mainDiv() .

I want to call only the subDiv() function when I press subDiv. How can I achieve this?

CODE:

 <div onclick="mainDiv()"> show main div <div onclick="subDiv()"> show sub div </div> </div> <script type="text/javascript"> function mainDiv(){ alert("main div is clicked"); } function subDiv(){ alert("sub div is clicked"); } </script> 
+4
source share
4 answers

use e.stopPropogation()

HTML

 <div onclick="subDiv(event)"> //<--- pass event parameter 

Javascript

 function subDiv(e){ if(e.stopPropagation){ // check stoppropogation is avilable e.stopPropagation(); //use stopPropogation }else{ e.cancelBubble = true; // for ie8 and below } alert("sub div is clicked"); } 
+3
source

You can use stopPropagation in all browsers except IE8 (and older ones from the same company). But if you want to be compatible, you must use the solution described in quirksmode :

  <div onclick="subDiv(event)"> function subDiv(e){ e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); alert("sub div is clicked"); } 

Demonstration

+3
source
 <script type="text/javascript"> function mainDiv() { alert("main div is clicked"); } function subDiv(e) { if (!e) e = window.event; //IE9 & Other Browsers if (e.stopPropagation) { e.stopPropagation(); } //IE8 and Lower else { e.cancelBubble = true; } alert("sub div is clicked"); } 

+1
source

try it

  <div onclick="mainDiv()"> show main div <div onclick="subDiv(event);"> show sub div </div> </div> <script type="text/javascript"> function mainDiv(){ alert("main div is clicked"); } function subDiv(arg){ arg.stopPropagation(); alert("sub div is clicked" + arg); } </script> 

To support IE 8 and lower use arg.cancelBubble

0
source

All Articles