RooksStrife
RooksStrife

Reputation: 1747

Closing a menu when a click is not on the menu by removing a class?

I have seen quite a bit on this topic of closing a menu when a click is not on the menu, but the question I have is, can you simply right the below code to be - if you do not click on #menu > ul > li > a removeClass open. Something like onclick !== css...?

$('#cssmenu > ul > li > a').on('click', function(){
        $("#cssmenu ul").removeClass("open");
    }); 

Upvotes: 0

Views: 40

Answers (1)

VaMoose
VaMoose

Reputation: 196

Would something like this work?:

HTML:

<div class="container">
<div id="cssmenu" class="open">
        Content goes here
</div>
</div>

CSS:

.container {
    width: 100%;
    height: 100%;   
}

#cssmenu {
    width: 50px;
    height: 50px;
    display: inline-block;
    background: #000;
}

.open {
    background: green !important;
}

And finally JS:

$(document).mouseup(function (e) {
var element = $("#cssmenu");

if (element.has(e.target).length === 0 && !element.is(e.target)) {
    // click outside of the element
    element.removeClass("open");
}
});

jsFiddle

Upvotes: 1

Related Questions