Henrik Petterson
Henrik Petterson

Reputation: 7094

Removing class if click outside of div (targetting class)

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.

Upvotes: 0

Views: 9943

Answers (2)

Anil Sharma
Anil Sharma

Reputation: 125

$(document).on("click", function(e) {  if ($(e.target).is(".trigger") === false) {
      $(".menu").hide();
    }
  });

Upvotes: 0

NemoStein
NemoStein

Reputation: 2098

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>

Upvotes: 5

Related Questions