2

I have number of drop down menu's which gets called with a onClick event right below those specific div's,and i also have a window.onclick set inorder to retract those dropdowns(which are active) when a user clicks elsewhere.

Now,when i click on a div(which has a dropDown) the drop down is getting activated(menu gets created) and simultaneously retracting (because of the window.click )

The menu's are getting created and getting destroyed at the same time!,Any work arounds to perform the window.onclick iff the clicked element is not on of the div's with a dropdown??

Silly question,from a beginner.. thanks in advance!!

here's a sample code!!.. the onclick on the div is supposed to bring out the menu -- and the window.onclick is supposed to retract the menu(all he menu's which are expanded)

<html>
    <style type="text/css">
    .bar{
    width: 30px;
    height: 30px;
    background-color: black;
    display: none;
    }
    </style>
    <script type="text/javascript" >
    function fire(){
    document.getElementById("bar").style.display="block";
    }
    window.onclick=unfire;
    function unfire(){
    if(document.getElementById("bar").style.display== "block")
    document.getElementById("bar").style.display="none";
    }
    </script>
    <input type="button" value="foo" onclick="fire()">
    <div id="bar" class="bar"></div>
    </html>

Edit:added the code sample

Vivek Chandra
  • 4,240
  • 9
  • 33
  • 38
  • possible duplicate of [How to stop event propagation with inline onclick attribute?](http://stackoverflow.com/questions/387736/how-to-stop-event-propagation-with-inline-onclick-attribute) – Felix Kling Dec 18 '11 at 13:04

4 Answers4

1
function doSomething() {
   if (this.id == "myId") return;
   // else do Something
}
abcde123483
  • 3,885
  • 4
  • 41
  • 41
1

You can call e.stopPropagation() (browsers) or e.cancelBubble = true (IE) to prevent the event from propagating up the tree.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

this will happen because of a mechanism called "Event bubbling", which will likely not just firing your event for the specific DOM element, but will also continue to raise your event from your child DOM element(s), until it reach the very beginning of your page.

using jquery library for example, provides us with a method to prevent this default action from happening (event.stopPropagation() ).

I don't know exactly if native JS code can achieve the same behavior, but let me know if you can use jQuery, and I will provide you with code example.

thanks,

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Mohammed Swillam
  • 9,119
  • 4
  • 36
  • 47
0

You want to trigger onmousedown on the divs instead.

Babiker
  • 18,300
  • 28
  • 78
  • 125