admin管理员组

文章数量:1335664

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.

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.

Share Improve this question edited May 22, 2015 at 17:02 Henrik Petterson asked May 22, 2015 at 17:00 Henrik PettersonHenrik Petterson 7,10421 gold badges80 silver badges157 bronze badges 2
  • 1 Post a plete code example in your question please. – j08691 Commented May 22, 2015 at 17:02
  • 1 Dupe of stackoverflow./questions/152975/… – j08691 Commented May 22, 2015 at 17:04
Add a ment  | 

2 Answers 2

Reset to default 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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#" class="trigger">menu</a>
<div class="menu">Hello</div>

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

本文标签: javascriptRemoving class if click outside of div (targetting class)Stack Overflow