Reputation: 359
Hello I created an on click nav bar for my homepage. I would like that the user clicks and then the nav bar opens. My code does work, however it only works one or two times and then it doesn't work the third time until I refresh the page.
Does anyone know why this is?
var sliderMenu = document.getElementById("slider-menu");
var close = document.getElementById("X");
sliderMenu.addEventListener("click", (event) => {
activate();
console.log(event)
});
close.addEventListener("click", (event) => {
closeNav();
});
function activate(event) {
var sliderMenuOpen = document.getElementById("slider-menu-open");
sliderMenuOpen.classList.toggle("width");
}
function closeNav(event) {
var sliderMenuOpen = document.getElementById("slider-menu-open");
sliderMenuOpen.classList.toggle("width-close");
}
<div class="slider-menu" id="slider-menu">
<p>More</p>
</div>
<div class="slider-menu-open" id="slider-menu-open">
<a id="X" href="">X</a>
<a href="">Carpet Cleaning</a>
<a href="">Blinds</a>
<a href="">Flooring</a>
<a href="">Rugs</a>
</div>
</div>
Upvotes: 0
Views: 160
Reputation: 4388
Try something like this instead. It removes the need for the extra class width-close
// i moved this to outside the functions so that you don't have to keep
// unnecessarily setting sliderMenuOpen
var sliderMenuOpen = document.getElementById("slider-menu-open");
var sliderMenu = document.getElementById("slider-menu");
var close = document.getElementById("X");
sliderMenu.addEventListener("click", (ev)=>{
sliderMenuOpen.classList.add("width");
});
close.addEventListener("click", (ev)=>{
sliderMenuOpen.classList.remove("width");
});
If you check the DOM with your old code you'll notice that they'll both be active (or inactive) at the wrong times after clicking close and open a few times.
Upvotes: 1
Reputation: 157
If you could share your CSS that would be helpful.
Whilst I'm not sure what your CSS is doing, the issue could be that you are toggling width
when clicking More
and width-close
when clicking X
.
On clicking More
you add width
class, then on clicking close you add width-close
then when you click open again it REMOVES width
(instead of adding it which is what it did the first time). then you click close and it adds width-close
again on its own.
this could be the cause, but without seeing the CSS I'm not sure.
It could be better if there was just one toggle function for both the close and the open which the X and the More would both use. You could then update the More
text to say Less
when the menu is open
Upvotes: 0