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.
- 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();
}
});
本文标签: javascriptRemoving class if click outside of div (targetting class)Stack Overflow
版权声明:本文标题:javascript - Removing class if click outside of div (targetting class) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742380025a2463916.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论