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

Utilizing AngualarJS to bind data to intricate objects using the $resource functionality

Currently, I am working on a restful service that retrieves an order along with a list of items. In my project, I am developing a screen where users can edit specific items within the order. To achieve this, I need to display the list of items before locat ...

React element featuring various interfaces

Currently, I am working on styling a React component in a way that allows for either horizontal or vertical styling without using flexbox. My question is, how can I pass styles down to the component in a way that applies individual styles to the child ele ...

How can I determine the specific quantity of XPATH links with unique identifiers in Selenium?

Seeking automation with Python3 and selenium to streamline searches on a public information site. The process involves entering a person's name, selecting the desired spelling (with or without accents), navigating through a list of lawsuits, and acces ...

ajax is now blocking the use of Window.location

I am facing an issue with window.location while working on an ajax request. Here is the code snippet for my ajax request: function login(){ var u = document.getElementById("username").value; var p = document.getElementById("password").value; ...

Does Firebase only send a single input value instead of a Span?

I am currently facing an issue with pushing data into my firebase database. I have successfully incorporated one user input field into the process. However, now I am attempting to include a span value in my database, which changes based on a slider that co ...

Do you have to host a node server to run Angular applications?

(say) I am currently working on a project that utilizes Laravel or PHP for the back-end and Angular for the front-end. In my setup, I am using angular.js files from a CDN, which should work fine. However, I find myself confused when tutorials and books me ...

The default selection for React Material Multiselect items is not being chosen

Currently, I am working on implementing the React Material autocomplete component that includes a multiple-values checkbox. However, it seems like there is an issue with the defaultValue prop and the checkboxes example. Even though I set defaultValue to a ...

The core-icons icon doesn't appear as intended in version 1.2.1 of Polymer

Currently, I am working with Polymer version 1.2.1 and have included core-icons in my elements.html file using the following import statement: <link rel="import" href="/bower_components/core-icons/social-icons.html"> Within a custom Polymer element ...

Codeigniter flashdata feature malfunctioning following the deletion of a record

Hello everyone! I am a newcomer to CodeIgniter and I am currently working on implementing flashdata to display a "successful" message after deleting a record. My approach involves using jQuery to handle the data presentation. Here is the code snippet from ...

JavaScript layout: Thymealf

I have a unique thymeleaf template like so: <body> <div id="layout"> <!-- Menu toggle --> <a href="#menu" id="menuLink" class="menu-link"> <!-- Hamburger icon --> <span>& ...

Using PHP and MySQL to handle data submission through the POST method

When I send data to post[submit] and post[request], it's coming from two separate buttons. Even though I successfully submitted user_id to post[submit], I'm encountering difficulty in echoing the user_id in the request portion (post[request]). ...

Finding items in the database using their identification numbers

I have a scenario where I am accepting a list of IDs in my request, for example [1,2,3]. How can I use typeorm and querybuilder to retrieve only objects with these IDs from my database? I attempted the following: if(dto.customersIds){ Array.prototype. ...

Improving Performance in Vue by Reducing `$set` Usage

Sharing my code snippet below <div v-for="namespace in chosenNamespaces" v-bind:key="namespace.id"> <!-- Select the Parameter --> <select @change="updateParameter($event, namespace.id)" v-model="currParameterValues[na ...

Troubleshooting: Unable to fetch CSS file in Node.js Express framework

I'm trying to access my .html file with localhost using node.js, but I'm facing an issue with loading the CSS that is included in the file. I am using the express framework for this purpose. Code: var express = require('express'); var ...

The functionality of IE's .attr disabled feature appears to be ineffective

My function to check if a product is available overnight is not functioning properly in Internet Explorer, although it works fine in other browsers. function checkOvernight() { id = $_2("[name='product']").val(); if(id.length > 0) { ...

Enhance Your Three.js Experience: Implementing Dots on Vertices

I am working with a wireframe sphere and looking to add dots to the vertices. Something similar to this image: https://i.sstatic.net/pzNO8.jpg. Below is all of my JavaScript code: var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( ...

The arrangement of imports in NodeJS can lead to unexpected errors

Having an issue with the order in which I include different models in my main server.js file using NodeJS. Below is the code from my product.js Product model file: var mongoose = require("mongoose"); var Dealer = require("./dealer.js") var productSc ...

AngularJS: How to automatically scroll to the bottom of a div

I cannot seem to scroll to the last message in my chat window. var app=angular.module('myApp', ['ngMaterial'] ); app.controller('ChatCtrl', function($window, $anchorScroll){ var self = this; self.messageWindowHeight = p ...

Passing a variable from index.html to a script in Angular

I am attempting to pass the array variable 'series' to the script in HTML. Is there a way to do this? app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app ...

Adjust the loading bar component in Material UI to allow for customizable color changes

I am currently learning how to use material ui. My goal is to customize the loading bar's CSS. I checked the documentation and utilized colorPrimary classes. However, the changes are not appearing as expected. Could you please guide me on how to resol ...