I working on this sliding menu. It can slide fine, but have problem to close it by clicking x.
You need to add actionListeners on buttons(links) rather than on document.
let slide = document.querySelector(".slide");
let slideOpen = document.querySelector(".slideOpen");
let slideClose = document.querySelector(".slideClose");
slideOpen.addEventListener('click', function(event) {
slide.style.width = "250px";
});
slideClose.addEventListener("click", () => {
slide.style.width = "0";
});
.slide { height: 100%; width: 0; position: fixed; z-index: 1; top: 0; left: 0; background-color: #111; overflow-x: hidden; transition: 0.5s; padding-top: 60px; }
.slide a { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 25px; color: #818181; display: block; transition: 0.3s; }
.slide a:hover { color: #f1f1f1; }
.slide .slideClose { position: absolute; top: 0; right: 25px; font-size: 36px; margin-left: 50px; }
<div style="font-size:30px;cursor:pointer" class="slideOpen">☰ open</div>
<div class="slide"> <ul>
<li> <a href="#" class="slideClose">×</a> </li>
<li> <a href="#">About</a> </li>
<li> <a href="#">Services</a> </li>
<li> <a href="#">Clients</a> </li>
<li> <a href="#">Contact</a> </li>
</ul> </div>
You are making addEventListener
to the whole document
instead make to particular element (open and close)..
Changes:
Added a new class openMenu
in the open menu element like,
<div style="font-size:30px;cursor:pointer" class="openMenu">☰ open</div>
Then added a new variable to store the element like,
let open = document.querySelector(".openMenu");
Then modified document.addEventListener
with open
and closeNav
respectively like,
open.addEventListener("click", () => {
openNav.style.width = "250px";
});
closeNav.addEventListener("click", () => {
openNav.style.width = "0";
});
And the changed snippet looks like,
let openNav = document.querySelector(".slideOpen");
let open = document.querySelector(".openMenu");
let closeNav = document.querySelector(".slideClose");
open.addEventListener("click", () => {
openNav.style.width = "250px";
});
closeNav.addEventListener("click", () => {
openNav.style.width = "0";
});
.slideOpen { height: 100%; width: 0; position: fixed; z-index: 1; top: 0; left: 0; background-color: #111; overflow-x: hidden; transition: 0.5s; padding-top: 60px; }
.slideOpen a { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 25px; color: #818181; display: block; transition: 0.3s; }
.slideOpen a:hover { color: #f1f1f1; }
.slideOpen .slideClose { position: absolute; top: 0; right: 25px; font-size: 36px; margin-left: 50px; }
<div style="font-size:30px;cursor:pointer" class="openMenu">☰ open</div>
<div class="slideOpen"> <ul>
<li> <a href="#" class="slideClose">×</a> </li>
<li> <a href="#">About</a> </li>
<li> <a href="#">Services</a> </li>
<li> <a href="#">Clients</a> </li>
<li> <a href="#">Contact</a> </li>
</ul> </div>