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.
- 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
2 Answers
Reset to default 5You 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();
}
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742380026a4432942.html
评论列表(0条)