mercredi 31 mars 2021

IF Else statement is not working with curly braces

I am creating a simple toggle menu using HTML, CSS, and js. I want that by clicking on the "toggle" button the menu should move to the "0px" position from left, and It works correctly. But not going to move on -"200px" from left. Because the width of the menu is 200px.

When I put curly braces for if statement the working stops. But after removing these braces code works perfectly.

// toggle menu for IE-9
const nav = document.querySelector( "#nav" );
const btn = document.querySelector( "#btn" );
btn.addEventListener( "click" , () => {
  var classes = nav.className.split( " " );
  var i = classes.indexOf( "show" );
  if (i >= 0 ) {
    classes.splice(i, 1);
  }
  else { 
    classes.push("show");
    nav.className = classes.join(" ");
  }
} );
body {
  background: #184d47;
}
/* stylin box */
.box {
  padding:20px;
  position: relative;
}
/* styling toggle button */
#btn {
  padding: 10px 25px;
  border: 2px solid #d44000;
  background: #d44000;
  color: #fff;
  font-family: arial;
  font-weight: bolder;
  letter-spacing: 1px;
  border-radius: 5px;
  user-select: none;
  transition: all .3s ease;
}
#btn:hover {
  background: #ff7a00;
  border: 2px solid #ff7a00;
  color: ff7a00;
  cursor: pointer;
  transition: all .3s ease;
}
/* styling list || nav */
#nav {
  width: 250px;
  height: 100%;
  background: #31326f;
  list-style: none;
  padding: 20px 0 0 0;
  position: fixed; 
  top: 60px;
  left: -250px;
  transition: all 1s ease;
}
#nav.show {
  left: 0px;
  transition: all 1s ease;
}
#nav li {
  padding: 10px 60px 10px 40px;
  border-bottom: 1px solid #dbf6e9;
  user-select: none;
  color: #fff;
  font-weight: bold;
  letter-spacing: 0.5px;
}
<div class="box">
  <buton id="btn" class="">Toggle</buton>
  <ul id="nav" class="">
    <li>HOME</li>
    <li>About</li>
    <li>Setting</li>
  </ul>
</div>

Aucun commentaire:

Enregistrer un commentaire