shihabudheen shihabudheen - 2 months ago 8
HTML Question

Neglect a function in JavaScript?

When I click mainDiv, the function

mainDiv()
will be invoked,
when I click subDiv, both
mainDiv()
and
subDiv()
functions are invoked.

I want to invoke only the
subDiv()
function when I click 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>

Answer

use e.stopPropogation()

HTML

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

javascrip

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