1

I have a fiddle for my project. I'm making a responsive navigation with dropdown menus. I currently have the dropdown items set to toggle when you click them. However, I'd like the dropdown to close if you click anywhere away from it.

I tried copying the code from a similar question, but it isn't working for me. I included it in the fiddle, but commented out so you can see the dropdowns work.

$(document).click(function(){
  $(".nav-dropdown").hide();
});

$(".nav-dropdown").click(function(e){
  e.stopPropagation();
}); 
0

1 Answer 1

2

Just put the e.stopPropagation() inside the toggle function.

Here is the working fiddle: http://codepen.io/anon/pen/MwLoKE

(If you want to have just one dropdown opened at a time, you'll also have to close the opened ones inside you toggle function.)

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

2 Comments

Awesome!! Thank you! Works great. If you could provide a hint towards how to close one dropdown when another opens, that would also be really cool. (I'm exceedingly new to jQuery and JavaScript). Otherwise I'll be working on figuring that out.
I used $('.nav-dropdown').not($(this).siblings()).hide(); and it seems to work!

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.