Creating a Responsive Navigation Menu with jQuery

Here is the responsive navigation menu with a stylish hamburger icon. We can create this type of menu using HTML, CSS, and jQuery.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="styles.css">
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <script src="script.js"></script>
  <title>Responsive Navigation Bar</title>
</head>
<body>

<nav class="topnav" id="myTopnav">
  <a href="#home" class="active">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <a href="#about">About</a>
  <a href="javascript:void(0);" class="icon" id="menuIcon">
    <i class="fa fa-bars"></i>
  </a>
</nav>

<div style="padding-left:16px">
  <h2>Responsive Navigation Bar</h2>
  <p>Resize the browser window to see how it works.</p>
</div>

</body>
</html>
CSS
body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

nav {
  overflow: hidden;
  background-color: #333;
}

nav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

nav a:hover {
  background-color: #ddd;
  color: black;
}

nav a.active {
  background-color: #04AA6D;
  color: white;
}

nav .icon {
  display: none;
}

@media screen and (max-width: 600px) {
  nav a:not(:first-child) {display: none;}
  nav a.icon {
    float: right;
    display: block;
  }
}

@media screen and (max-width: 600px) {
  nav.responsive {position: relative;}
  nav.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  nav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }
}
JavaScript
$(document).ready(function () {
  $("#menuIcon").click(function () {
    var nav = $("#myTopnav");
    nav.toggleClass("responsive", !nav.hasClass("responsive"));
  });
});

Leave a Reply

Your email address will not be published. Required fields are marked *