How to create a collapsible sidepanel menu with CSS and JavaScript?

CSSWeb DevelopmentFront End TechnologyJavascript

Following is the code to create a collapsible sidepanel menu −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.sideNav {
   width: 0;
   height: 300px;
   position: fixed;
   z-index: 1;
   top: 0;
   left: 0;
   background-color: rgb(46, 218, 195);
   overflow-x: hidden;
   padding-top: 60px;
   transition: 0.5s;
}
.sideNav a {
   padding: 8px 8px 8px 32px;
   text-decoration: none;
   font-size: 25px;
   color: #000000;
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   display: block;
   transition: 0.3s;
}
.sidenav a:hover {
   color: #f1f1f1;
}
.sideNav .closeBtn {
   position: absolute;
   top: 0;
   right: 25px;
   font-size: 36px;
   margin-left: 50px;
}
button {
   padding: 15px;
   background-color: rgb(0, 27, 145);
   color: rgb(255, 255, 255);
   font-size: 20px;
   border: none;
   border-radius: 2%;
}
</style>
</head>
<body>
<nav class="sideNav">
<a href="#" class="closeBtn">×</a>
<a href="#">Login</a>
<a href="#">Register</a>
<a href="#">Home</a>
<a href="#">About Us</a>
</nav>
<button class="openSideNav">Click here to open sideNav</button>
<section>
<h1>This is some random heading</h1>
<h1>This is another heading</h1>
<h1>Here is another random heading</h1>
</section>
<script>
let openBtn = document.querySelector(".openSideNav");
openBtn.addEventListener("click", () => {
   showNav();
});
let closeBtn = document.querySelector(".closeBtn");
closeBtn.addEventListener("click", () => {
   hideNav();
});
function showNav() {
   document.querySelector(".sideNav").style.width = "30%";
}
function hideNav() {
   document.querySelector(".sideNav").style.width = "0";
}
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the open sideNav button −

raja
Published on 06-Apr-2020 11:28:49
Advertisements