Slartib42tfast
Slartib42tfast

Reputation: 45

Select all elements except a certain class

I'm trying to hide .menu_branch using jQuery slideUp() only if the user clicks off of .menu_root. I'm not getting any errors but the click() function is executing even if .menu_root is clicked. Any ideas? jQuery or straight JavaScript are both fine by me. Thanks!

HTML:

<span class="menu_root">Menu</span>
<ul class="menu_branch">
    <li><a href="#">Home</a></li>
    <li><a href="#">FAQ</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
</ul>

CSS:

.menu_branch {
    display:block;
}

Jquery:

$("body:not(.menu_root)").click(function(){
    $(".menu_branch").slideUp("fast");
});

I've also tried:

$("body").not(".menu_root").click(function(){
    $(".menu_branch").slideUp("fast");
});

As well as replacing body with * in both instances, all with the same result.

Upvotes: 2

Views: 84

Answers (4)

Moob
Moob

Reputation: 16184

Late to the party again but this should work for you. Clicking .menu_root will toggle the menu. Clicking anywhere else will close it (if its open).

$(document).on("click", function(e) {//When the user click on any element:
    if($(".menu_branch").is(":visible")){//If the menu is open...
        $(".menu_branch").slideUp("fast");//close it.
    } else if ($(e.target).hasClass("menu_root")){//Otherwise, if the user clicked menu_root...
        $(".menu_branch").slideDown("fast");//open it.
    }
});

http://jsfiddle.net/xGfTq/

Upvotes: 1

chriz
chriz

Reputation: 1345

try

$(document).click(function () {
    $(".menu_branch").slideUp("fast");
});
$('.menu_root').click(function () {
   return false;
})

Upvotes: 0

Dan1121
Dan1121

Reputation: 83

You can try this:

$("body").click(function(event){
    if ( $(event.target).hasClass("menu_root") ) {
        return false; 
    }
    $(".menu_branch").slideUp("fast");
});

http://jsfiddle.net/WzW2D/2/

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

One possible solution is to prevent the propagation of click event from menu_root

$(document).click(function () {
    $(".menu_branch").slideUp("fast");
});
$('.menu_root').click(function (e) {
    e.stopPropagation();
})

Demo: Fiddle

Your code will ignore a body element with class menu_root like <body class="menu_root">

Upvotes: 3

Related Questions