2

I'm using jQuery to make a simple drop down menu:

<script>                    
  $("#optionsLink").click(function(){                   
    $("#optionsMenu").slideToggle();
  });
</script>

It works fine but I would like the menu to disappear when the user clicks elsewhere on the screen. A bit like your standard windows drop down menu. Clicking on "File" in my browser will display the drop down menu but clicking somewhere else, anywhere on a page for example, will hide the menu.

How would I go about implementing something like this?

3
  • can you share the HTML of the menu, and related CSS / JS ? A jsfiddle would be great! jsfiddle.net Commented Sep 11, 2013 at 20:32
  • @msturdy There's really no need to show HTML because one can infer that #optionsMenu is the menu and the rest of the question just refers to jQuery. Commented Sep 11, 2013 at 20:34
  • Just edited my answer. Commented Sep 11, 2013 at 20:42

2 Answers 2

4

Just use

$("#optionsLink").click(function(e){
  $("#optionsMenu").slideToggle();
  e.stopPropagation(); 
});

$(document).click(function(){                   
  $("#optionsMenu").slideUp();
});

"slideToggle" would toggle the menu every time you click anywhere and I don't think that's what you want

.stopPropagation() will prevent the event from bubbling up to the document when you click inside of the #optionsLink

Sign up to request clarification or add additional context in comments.

2 Comments

Your solution works, but clicking within #optionsMenu also slides #optionMenu up. How could I change that to "document except #optionsMenu".click -> slideUp ?
just use stopPropagation on $('#optionsMenu') as well
2

Try this:

$("#optionsLink").click(function(){                   
    $("#optionsMenu").slideToggle();
  });
//new part
$(':not(#optionsLink, #optionsLink *)').click(function() {
    $("#optionsMenu").slideUp();
});

Targeting #optionsLink means you just have one drop-down. If you would have more you should hava class instead, maybe like .optionsLink.

2 Comments

I tried your proposed solution, but now when I click on #optionsLink it displays #optionsMenu but #optionsMenu automatically slides up as soon as it's finished sliding down. I'm very new to jQuery, but doesn't your code tell him to slide up when #optionsLink is not being clicked?
@user2018084, the :not(#optionsLink) means all elements besides #optionsLink. Try my updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.