How to create a responsive navigation menu with jQuery



Image not found!!

Creating a responsive navigation menu with jQuery involves several steps, including HTML markup, CSS styling, and jQuery scripting. Below is a basic example to get you started:

  1. HTML Markup:
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive Navigation Menu</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="navbar"> <a href="javascript:void(0);" class="icon" onclick="toggleMenu()"> <i class="fa fa-bars"></i> </a> <div id="myLinks"> <a href="#home">Home</a> <a href="#about">About</a> <a href="#contact">Contact</a> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="script.js"></script> </body> </html>
  1. CSS Styling (styles.css):
css
.navbar { overflow: hidden; background-color: #333; } .navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 20px; text-decoration: none; font-size: 17px; } .navbar a:hover { background-color: #ddd; color: black; } .navbar a.icon { display: none; } @media screen and (max-width: 600px) { .navbar a:not(:first-child) {display: none;} .navbar a.icon { float: right; display: block; } } @media screen and (max-width: 600px) { .navbar.responsive {position: relative;} .navbar.responsive .icon { position: absolute; right: 0; top: 0; } .navbar.responsive a { float: none; display: block; text-align: left; } }
  1. jQuery Script (script.js):
javascript
function toggleMenu() { var x = document.getElementById("myLinks"); if (x.style.display === "block") { x.style.display = "none"; } else { x.style.display = "block"; } } $(document).ready(function(){ $(".navbar a.icon").click(function() { $(".navbar").toggleClass("responsive"); }); });

In this example:

  • The HTML markup defines a navigation bar with links.
  • CSS provides the styling for the navigation bar and handles responsiveness using media queries.
  • jQuery script toggles the visibility of the navigation links when the menu icon is clicked and adds/removes the "responsive" class to the navigation bar to enable mobile responsiveness.

Make sure to include the jQuery library in your project for this code to work. You can download the library from the jQuery website or include it via a CDN like in the provided example.