Reputation: 67
I've seen a few similar questions but my menu open/close functionality is operated by slideToggle() rather than a class, and I'd rather not change my CSS to make it work.
I need the menu to close when the user clicks anywhere else on the page.
HTML:
<div class="select">
<button class="select__selector">Reveal menu</button>
<ul class="select__select">
<li class="select__option"><a></a></li>
<li class="select__option"><a></a></li>
...
</ul>
</div>
JS:
var langTrigger = jQuery('.select__selector');
var langList = jQuery('.select__select');
// Trigger active state.
langTrigger.click(function() {
langTrigger.toggleClass('open');
langList.slideToggle(200);
});
// Close list when page is loading.
langList.click(function() {
langTrigger.click();
});
I've tried a few things but this was as close as I got.
if((langTrigger).hasClass('open')) {
jQuery('body').on('click', function() {
langList.css({display: 'none'});
});
}
Upvotes: 0
Views: 153
Reputation: 867
add a div and position it over your whole website like this:
<div class="overlay"</div>
.overlay{
display: none;
position: fixed;
width: 100%;
height: 100%;
z-index: 9999;
}
then something like this:
$('.opensmenu').click(function(){
$('.menu').toggle();
$('.overlay').show();
});
$('.overlay').click(function(){
$('.menu').hide();
$(this).hide();
});
Upvotes: 1