5

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>
fragilewindows
  • 1,394
  • 1
  • 15
  • 26
shihabudheen
  • 696
  • 8
  • 26

4 Answers4

3

You might use stopPropagation in all browsers except IE8 (and older ones from the same company). But if you want to be compatible, you should 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

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
3

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");
}
bipen
  • 36,319
  • 9
  • 49
  • 62
1
<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");

}

Anshuman Jasrotia
  • 3,135
  • 8
  • 48
  • 81
0

Try this

    <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

karthick
  • 11,998
  • 6
  • 56
  • 88