Reputation: 820
I am trying to create a css side menu but when I close the menu, setting div container width to 0, the links are still visible.
Here is the jsfiddle - https://jsfiddle.net/atLvp6k7/
Interestingly, when I set the menu to the right of the screen I do not have the same problem. Do I need to add margin properties to the a items?
<div id="side-menu" class="side-nav">
<img id="close-side" src="https://floraisabelle.com/assets/images/hamburger-menu.png?v=aa3f825eb7" alt="">
<a class="" href="#">Hi</a>
<a class="" href="#">Hi</a>
<a class="" href="#">Hi</a>
<a class="" href="#">Hi</a>
</div>
var isOpen = false;
document.getElementById('close-side').addEventListener("click", function(){
if (isOpen) {
document.getElementById("side-menu").style.width = "0px";
document.getElementById("close-side").style.marginLeft = "0px";
isOpen = false;
} else {
document.getElementById("side-menu").style.width = "250px";
document.getElementById("close-side").style.marginLeft = "181px";
isOpen = true;
}
})
.side-nav {
transition: .5s;
height: 100%;
width:0;
background-color: rgba(120, 120, 120, 0.1);
position: fixed;
top: 0;
left: 0;
z-index: 1;
}
#close-side {
margin-left: 0;
margin-top: 5px;
transition: linear .5s;
position: fixed;
}
Upvotes: 1
Views: 348
Reputation: 1277
you can change the margin of the sidebar instead of width....
here is how to do it -
document.getElementById('close-side').addEventListener("click", function(){
if (isOpen) {
document.getElementById("close-side").style.marginLeft = "-100px";
isOpen = false;
} else {
document.getElementById("close-side").style.marginLeft = "0px";
isOpen = true;
}
})
and place the button (close-side) outside the sidebar div
<img id="close-side" src="https://floraisabelle.com/assets/images/hamburger-menu.png?v=aa3f825eb7" alt="">
<div id="side-menu" class="side-nav">
<a class="" href="#">Hi</a>
<a class="" href="#">Hi</a>
<a class="" href="#">Hi</a>
<a class="" href="#">Hi</a>
</div>
now apply following css for the transition effect -
.side-nav
{
transition: all 0.5s ease;
}
Upvotes: 1
Reputation: 522
css
.side-hidden a {
display: none;
}
HTML
<div id="side-menu" class="side-nav side-hidden">
SCRIPT
var isOpen = false;
document.getElementById('close-side').addEventListener("click", function(){
if (isOpen) {
document.getElementById("side-menu").classList.add('side-hidden');
document.getElementById("side-menu").style.width = "0px";
document.getElementById("close-side").style.marginLeft = "0px";
isOpen = false;
} else {
document.getElementById("side-menu").classList.remove('side-hidden');
document.getElementById("side-menu").style.width = "250px";
document.getElementById("close-side").style.marginLeft = "181px";
isOpen = true;
}
})
I have updated your fiddle also https://jsfiddle.net/atLvp6k7/1/
there is no need for isOpen Variable
if(document.getElementById("side-menu").classList.contains('side-hidden')){
alert('isClosed');
}else{
alert('isOpen');
}
Upvotes: 1