Reputation: 77
I am trying to create a menu sliding in from the right when a hamburger menu is clicked. I want the menu to close when the user clicks on the X (hamburger menu animates to an X when clicked) or when the user clicks anywhere else on the screen.
<button class="hamburger hamburger--spin" type="button">
<span class="hamburger-box" onclick="openNav()">
<span class="hamburger-inner"></span>
</span>
</button>
<div id="sideMenu-animated" class="sideMenu">
<a href="#">Item 1</a>
<a href="#">Item 2</a>
<a href="#">Item 3</a>
<a href="#">Item 4</a>
<a href="#">Item 5</a>
<a href="#">Item 6</a>
</div>
<script>
function openNav() {
document.getElementById("sideMenu-animated").style.width = "400px";
}
function closeNav() {
document.getElementById("sideMenu-animated").style.width = "0";
}
</script>
<script>
var hamburger = document.querySelector(".hamburger");
hamburger.addEventListener("click", function() {
hamburger.classList.toggle("is-active");
}
);
</script>
Basically right now, I have it set up so when the user clicks on the menu icon, it becomes active and animates the menu icon into an X. Doing this also triggers my openNav() function (makes menu items come into view).
Upvotes: 1
Views: 1915
Reputation: 1065
It seems you have everything in place but do not have your close method being called.
I would start by removing your onclick
in your HTML. You can check for the is-active
class inside your click handler to see if the menu should be opening or closing via the button click.
hamburger.addEventListener("click", function() {
this.classList.toggle("is-active");
if (this.classList.contains('is-active')){
openNav();
} else {
closeNav();
}
}
For clicking on the page to close, I would try to incorporate an 'overlay' that is behind the menu and over the page content. Make it cover the entire page view.
You can then add a click handler to that in the same way as the button to trigger the hamburger button click.
Upvotes: 1