Automatically collapse the responsive menu upon selecting a menu item

I have implemented a custom JavaScript code for a basic open/close menu movement on multi-page websites. The code works by closing the menu only when the user clicks the menu symbol. However, I now need to incorporate this code into a one-page website and make it so that the menu closes after a user clicks on a menu item. Since I have limited experience in JavaScript, I am seeking assistance in solving this issue.

The JavaScript code:

$(document).ready(function() {
    var n = '#nav', no = 'nav-open';
    $('#nav-menu').click(function() {
        if ($(n).hasClass(no)) {
            $(n).animate({height:0},300);
            setTimeout(function() {
                $(n).removeClass(no).removeAttr('style');
            },320);
        }
        else {
            var newH = $(n).css('height','auto').height();
            $(n).height(0).animate({height:newH},300);
            setTimeout(function() {
                $(n).addClass(no).removeAttr('style');
            },320);
        }
    });
});

The HTML:

<!-- Navigation Bar -->
<div class="nav-hold">
  <div class="nav-bar"> 
    <a href="#one" class="nav-logo"><img src="images/logo.png" alt="logo" /></a>
    <a href="#one" class="nav-logo-text">Company name</a>
    <a id="nav-menu" class="nav-menu-symbol">&#9776;<!-- menu symbol --></a>
    <a class="nav-menu">Menu</a>
    <ul class="nav-list" id="nav">
      <li><a href="#one">Top</a></li>
      <li><a href="#two">About us</a></li>
      <li><a href="#three">Services</a></li>
      <li><a href="#four">Portfolio</a></li>
      <li><a href="#five">Contact</a></li>
    </ul>
  </div>
</div>
</div>

Answer №1

modify

$('#nav-menu').click(function() {

in case you prefer the menu to close only when clicking on the li element

$('#nav li').click(function() {

or if you want the menu to close with both the li and menu icon

$('#nav-menu, #nav li').click(function() {

Answer №2

It seems like the click function is only bound to the menu symbol in this code snippet. However, it might be beneficial to combine the symbol and text within a single element for better organization. Additionally, consider using jQuery's slideToggle() method to smoothly slide the navigation menu up or down upon clicking. Here's an example:

$(document).ready(function() {
    $('#nav-menu').click(function() {
      $('#nav').slideToggle(300);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav-hold">
  <div class="nav-bar"> 
    <a href="#one" class="nav-logo"><img src="images/logo.png" alt="logo" /></a>
    <a href="#one" class="nav-logo-text">Company name</a>
    <a id="nav-menu" class="nav-menu-symbol">
      <span>&#9776;</span>
      <span>Menu</span>
    </a>
    <ul class="nav-list" id="nav">
      <li><a href="#one">Top</a></li>
      <li><a href="#two">About us</a></li>
      <li><a href="#three">Services</a></li>
      <li><a href="#four">Portfolio</a></li>
      <li><a href="#five">Contact</a></li>
    </ul>
  </div>
</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...

retrieve object from s3 using angular and open it as a pdf

I'm attempting to access a file from an s3 bucket using Angular and display it as a PDF. I have a node service set up to retrieve the object, which I then call from Angular. However, when I try to open the PDF in Angular, it appears as a blank (white) ...

What is the best way to position Scroll near a mat row in Angular?

With over 20 records loaded into an Angular Material table, I am experiencing an issue where clicking on the last row causes the scroll position to jump to the top of the page. I would like the scroll position to be set near the clicked row instead. Is th ...

Storing POST Request Data in Express

I want to use a single API endpoint for both GET and POST requests. My goal is as follows: Send multiple POST requests to /api/users with data like: {'id': 2, is_valid: 'true'} Retrieve this data by fetching the same API URL later on ...

Customizing the starting number of rows per page in TablePagination from material-ui

As a newcomer to using materials, I am looking to customize the table pagination to show 'n' number of rows, for example 10, and remove the "Rows per page" dropdown. <TablePagination rowsPerPageOptions={[]} component="div" ...

Adaptable Website Design (Without Header)

Check out my current website layout on codepen. I'm looking for a more responsive way to code this with CSS, so that the text doesn't get pushed over when the window is resized. Also, I want to improve the efficiency of coding the CSS for this l ...

Definition for TypeScript for an individual JavaScript document

I am currently attempting to integrate an Ionic2 app within a Movilizer HTML5 view. To facilitate communication between the Movilizer container client and the Ionic2 app, it is crucial to incorporate a plugins/Movilizer.js file. The functionality of this f ...

Load Express JS router middleware conditionally based on certain conditions

In my Express JS code, I have implemented a middleware that defines specific end-points on a router for user login and logout. However, I am now integrating a new authentication method where the auth token is received from a different service. In this case ...

What is the method used for defining an element within an array in JavaScript?

As I am new to JavaScript, I find myself trying to organize callbacks within an array. An example of what I have been working on: items = [ "test" = async message => { let userCoins = editCurrency('fetch', message.guild. ...

Capable of retrieving response data, however, the label remains invisible in the dropdown menu

Upon selecting a country, I expect the corresponding city from the database to be automatically displayed in the dropdown menu. While I was able to retrieve the state response (as seen in the console output), it is not appearing in the dropdown menu. Inte ...

Utilizing Express.js: A Guide to Fetching File Downloads with a POST Method

Although GET requests are successful, I am facing challenges when using POST to achieve the same results. Below are the different code snippets I have attempted: 1. app.post("/download", function (req, res) { res.download("./path"); }); 2. app.post ...

Varied selection menu feature

Looking to build a new component: The idea is to create something similar to a dropdown list. I aim to incorporate this component into every cell (td) of table rows. The challenge lies in displaying the second div (item list) under the first div, but abov ...

Troubles with HTML and div elements

I have a specific need to dynamically load HTML into a div container with the style attribute overflow set to hidden. I have implemented next and previous buttons for navigation, but I am facing an issue where the content overlaps at the beginning and end ...

The data object received from the $.get method may come back as either undefined

The code below demonstrates the process of converting a string variable 'data' back into an object using $( data ). However, when trying to execute commands like $(data).find(".className").text() or $(data).find(".someClass").html(), it results i ...

Transitioning to the Full Website with PHP Sessions - Discrepancies in Styling

I've encountered an issue when trying to switch from a mobile site to a full site using sessions. The styles on the full site do not load unless I refresh the page, at which point they finally appear. On my mobile page, there's a link that direct ...

Enhance the functionality of Woocommerce email notifications by incorporating a customized VAT field

I have exhausted all options and tried various email hooks without success. I inherited an outdated PHP code that was developed by someone else, which I updated for new woocommerce hooks (since the code is 4 years old). Everything is functioning smoothly e ...

JavaScript asynchronous problem

When developing a simple Javascript function to validate user input for City and State, it encounters an issue with asynchronous behavior. The function checks if the user has entered values in the specified input fields and then proceeds to geocode the l ...

Progressively modifying related elements over time intervals

I have a specific list of p elements in my HTML code that I need to modify sequentially with a time interval of 1 second. Here is the HTML: <p>Changing first sentence!</p> <p>Second sentence ready!</p> <p>Third one coming up ...

The Link tag in the Hero.jsx file of Next.js is malfunctioning and failing to redirect to the intended URL

Having a problem with the button in my Hero.jsx component, part of the Page.js implementation. The button uses a Link tag to redirect to the url.js page, but it's not working as expected and showing an Error 404 page instead. I'm new to Next.js s ...

Obtain a specific portion of text from a string that resembles a URL

$("#index-link")[0].search = "?isNameChecked=False&isDateChecked=False&isStatusChecked=True" Is there a way to use jQuery to identify whether isStatusChecked is set to true or false in the given string? ...