Reputation: 487
I have a slide out menu that I want to close when the user clicks on the overlay. The menu closes but to open it again I have to click the toggle twice instead of once, where I'm I going wrong?Thanks. A sample page demonstrating this slideoutMenu
function expandOverlay() {
var overlay = document.createElement("div");
overlay.setAttribute("id", "overlay04");
overlay.setAttribute("class", "overlay04");
document.body.appendChild(overlay);
}
function restore() {
document.body.removeChild(document.getElementById("overlay04"));
}
// create menu variables
var slideoutMenu = $('.slideout-menu');
var slideoutMenuWidth = $('.slideout-menu').width();
$(document).ready(function() {
$('.slideout-menu-toggle').on('click', function(event) {
event.preventDefault();
// toggle open class
slideoutMenu.toggleClass("open");
// slide menu
if (slideoutMenu.hasClass("open")) {
slideoutMenu.animate({
left: "0px"
});
expandOverlay();
} else {
slideoutMenu.animate({
left: -slideoutMenuWidth
}, 250);
restore();
}
});
});
window.addEventListener('mouseup', function(event) {
var box = document.getElementById('menu_s');
if (event.target != box && event.target.parentNode != box) {
slideoutMenu.animate({
left: -slideoutMenuWidth
}, 250);
restore();
}
});
<nav>
<ul>
<li><a href="#" class="lag slideout-menu-toggle">open menu</a></li>
</ul>
</nav>
<!--begin slideout menu-->
<div id="menu_s" class="slideout-menu">
<h3>Last Week<a href="#" class="slideout-menu-toggle">×</a></h3>
<div class="fslide"></div>
<ul>
<li><a href="http://dundaah.com/">Dundaah</a></li>
<li><a href="http://pics.dundaah.com/">Pics</a></li>
<li><a href="http://blog.dundaah.com/">Blog</a></li>
<li><a href="http://music.dundaah.com/">Music</a></li>
</ul>
</div>
Upvotes: 1
Views: 613
Reputation: 221
I believe the problem here is that the class open is still on toggleMenu after the overlay is clicked.
Therefore, if you were to click open menu after closing, the click event would remove the open class from toggleMenu, resulting in the else part of the if statement being executed (which is to close the menu).
This is why 2 clicks are needed before the menu will be open if it was closed by clicking the overlay.
You could possibly try to toggleClass("open") when closing the menu by clicking on the overlay.
Upvotes: 5