0

I have a menu where user clicks on link and list appears via .addClass( "show-nav" ).

Here is jsFiddle with JS code:

jQuery(".nav-js-trigger").each(function(){
    this.onclick = function() {

        var hasClass;
        hasClass = jQuery(this).next().hasClass( "show-nav" );

        jQuery('.show-nav').removeClass('show-nav');

        if (hasClass === false) {
            jQuery(this).next().addClass( "show-nav" );
        }

    }
});

I want to remove the class show-nav if the user clicks outside of the div with class show-nav. How do I do this?

I have seen examples of e.target div ID but not class, particularly not a scenario like this.

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

2 Answers2

5

You can add an listener to the element with an event.stopPropagation() on it, and another listener to the body, to capture this event if not intercepted before.

Something like this:

$(".show-nav").on("click", function(event){
    event.stopPropagation();
});

$("body").on("click", function(event){
    $(".show-nav").hide(); // or something...
});

To simplify your use-case, here is a JSFiddle.

$(".trigger").on("click", function(event)
{
    $(".menu").toggle();
    event.stopPropagation();
});

$(".menu").on("click", function(event)
{
    event.stopPropagation();
});

$(document).on("click", function(event)
{
    $(".menu").hide();
});
.menu
{
    display: none;
    background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#" class="trigger">menu</a>
<div class="menu">Hello</div>
NemoStein
  • 2,088
  • 2
  • 22
  • 36
  • 1
    Can you please update the fiddle? I tried adding your code but it did not work unfortunately: http://jsfiddle.net/ghLn4nmL/2/ – Henrik Petterson May 22 '15 at 17:11
  • @HenrikPetterson, added jsfiddle and code snippet... I've changed your a bit (ok, a lot) to make it simpler and more flexible... – NemoStein May 22 '15 at 17:40
  • Thank you very much for the update, although now you can't hide the div when you click on menu again. If you see my original fiddle and click on menu twice, you will know what I mean: http://jsfiddle.net/ghLn4nmL/1/ -- I will bounty this question with 50 points once it is eligible. – Henrik Petterson May 22 '15 at 17:44
  • @HenrikPetterson, not a problem... Just updated the code again, changing the `.show()` to `.toggle()` in the `$(".trigger")` click listener... Could you try it again? – NemoStein May 22 '15 at 17:48
  • Excellent, although I do have one final request. The code needs to use it's original approach of adding the show-nav class to div. Is this still possible with your approach? – Henrik Petterson May 22 '15 at 17:52
0
$(document).on("click", function(e) {  if ($(e.target).is(".trigger") === false) {
      $(".menu").hide();
    }
  });
Andy
  • 49,085
  • 60
  • 166
  • 233
Anil Sharma
  • 125
  • 1
  • 6