Toggle the hamburger menu using JavaScript

How can I close my hamburger menu when clicking a link for one page navigation? The menu is functioning properly, but I need a way to close it. Unfortunately, I have limited knowledge of JS.

I only have the HTML and CSS for this:

HTML in index.html file

<nav>
<div id="menuToggle">
    <input type="checkbox"/>
    <span></span>
    <span></span>
    <span></span>

<ul id="menu" class="navbar-collapse">
        <li><a href="#1">Go to 1</a></li>
        <li><a href="#2">Go to 2</a></li>
        <li><a href="#3">Go to 3</a></li>
</ul>
</div>
</nav>

CSS in style.css file

*{
    margin:0;
    padding:0;
}
nav{
    position:fixed;
    z-index: 99999;
}
a{
    text-decoration: none;
    font-family: 'Lato', sans-serif;
    color: #000000;
    transition: color 0.3s ease;
}
a:hover{
    color: #999999;
}
#menuToggle{
    display: block;
    position: relative;
    top: 50px;
    left: 50px;
    z-index: 1;
    -webkit-user-select: none;
    user-select: none;
}

... (CSS continued as original) ...

@media only screen and (max-width:480px) { 
    #menuToggle input {
        top: 2px;
        left: -5px;
    }
}

Any assistance on how to close the hamburger menu would be greatly appreciated!

Answer №1

Utilize trigger .

$('#menu > li > a').on('click', function() {
  $("#menuToggle").find('input').trigger("click");
});
*{
margin:0;
padding:0;
}
nav{
position:fixed;
z-index: 99999;
}
a{
text-decoration: none;
font-family: 'Lato', sans-serif;
color: #000000;
transition: color 0.3s ease;
}
a:hover{
color: #999999;
}
#menuToggle{
display: block;
position: relative;
top: 50px;
left: 50px;
z-index: 1;
-webkit-user-select: none;
user-select: none;
}
#menuToggle input{
display: block;
width: 40px;
height: 32px;
position: absolute;
top: -7px;
left: -5px;
cursor: pointer;
opacity: 0;
z-index: 2;
-webkit-touch-callout: none;
}
#menuToggle span{
display: block;
width: 33px;
height: 4px;
margin-bottom: 5px;
position: relative;
background: #000000;
border-radius: 3px;
z-index: 1;
transform-origin: 4px 0px;
transition: transform 0.5s cubic-bezier(0.77,0.2,0.05,1.0),
background 0.5s cubic-bezier(0.77,0.2,0.05,1.0),
opacity 0.55s ease;
}
#menuToggle span:first-child{
transform-origin: 0% 0%;
}
#menuToggle span:nth-last-child(2){
transform-origin: 0% 100%;
}
#menuToggle input:checked ~ span{
opacity: 1;
transform: rotate(45deg) translate(-2px, -1px);
background: #000000;
}
#menuToggle input:checked ~ span:nth-last-child(3){
opacity: 0;
transform: rotate(0deg) scale(0.2, 0.2);
}
#menuToggle input:checked ~ span:nth-last-child(2){
opacity: 1;
transform: rotate(-45deg) translate(0, -1px);
}
#menu{
background-size:cover;
background-repeat:no-repeat;    
position: absolute;
width: 100vw;
height:100vh;
margin: -77px 0 0 -50px;
padding: 50px;
padding-top: 125px;
background-color: rgba(255,255,255,1);
list-style-type: none;
-webkit-font-smoothing: antialiased;
transform-origin: 0% 0%;
transform: translate(-100%, 0);
transition: transform 0.5s cubic-bezier(0.77,0.2,0.05,1.0);
}
#menu li{
padding: 10px 0;
font-size: 60px;
text-align: center;
}
#menuToggle input:checked ~ ul{
transform: scale(1.0, 1.0);
opacity: 1;
}

@media only screen and (max-width:480px) { 
#menuToggle input {
top: 2px;
left: -5px;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menuToggle">
  <input type="checkbox" />
  <span></span>
  <span></span>
  <span></span>

  <ul id="menu" class="navbar-collapse">
    <li><a href="#1">go to 1</a></li>
    <li><a href="#2">go to 2</a></li>
    <li><a href="#3">go to 3</a></li>
  </ul>
</div>

Note: Make sure to place your js code within document.ready.

$(function() {
 $('#menu > li > a').on('click', function() {
      $("#menuToggle").find('input').trigger("click");
    });
});

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

What is the best way to access a specific attribute of an HTML element?

Within my ng-repeat loop, I have set a custom attribute like this: <div ng-repeat="item in itemsList" stepType="{{item.stepType}}"> {{item.itemValue}} </div> The possible values for item.stepType are 'task' or 'action ...

Responsive jQuery drop-down navigation menu for touchscreen devices struggles with hiding one menu item while clicking on another

I'm currently working on implementing a dropdown navigation menu for touch devices utilizing jQuery. I have managed to successfully hide dropdowns when tapping on the menu item title or outside the navigation area. However, I am facing an issue where ...

AJAX Image Upload: How to Transfer File Name to Server?

Has anyone successfully uploaded an image to a web server using AJAX, but struggled with passing the file name and path to the PHP script on the server side? Here is the HTML code along with the JavaScript (ImageUpload01.php) that triggers the PHP: Pleas ...

Issue with FullPage.js scrollOverflow feature not properly accommodating loaded content

I am currently working on a full-page website and have opted to utilize the Fullpage.js plugin. However, I seem to be facing some challenges when it comes to loading content through an AJAX request. The pages are being populated with JSON content, but for ...

Is there a way to modify the standard width of semantic-ui sidebars?

I'm trying to adjust the width of semantic-ui sidebars, which are originally 275px wide. Where should I include the css/js code to make them wider or narrower? Here is their default code: .ui.sidebar { width: 275px!important; margin-left: -275 ...

Converting a jQuery/JSON/PHP object to a C# function

Hello everyone, I am new to JSON and I recently came across an example that uses PHP and jQuery (http://wil-linssen.com/entry/extending-the-jquery-sortable-with-ajax-mysql/). My goal is to take the serialized "order" object and utilize it in a C# method j ...

What is the most efficient method to match a list of titles with a distinct list of their associated links using Beautiful Soup 4 (bs

Update: I've found the solution! list_c = [[x, y] for x, y in zip(titleList, linkList)] Initial inquiry: In my project to scrape a recipe website using bs4, I encountered a challenge where the titles and links were not directly paired. After extracti ...

One way to change the cursor CSS property is by dynamically altering it based on scrolling behavior. This involves modifying the cursor property when scrolling

I'm attempting to adjust the cursor property within an Angular function. The issue I'm facing is that when I begin scrolling the webpage, the cursor changes to a pointer, but when I stop scrolling, it remains as a pointer. I've attempted to ...

Endless scrolling with redux and react

I'm facing an issue while trying to implement infinite scroll in a React-based application that utilizes Redux for state management. I am attempting to dispatch an action on page scroll but have been unsuccessful so far. Below is my code snippet: // ...

Lengthen the space between each item on the list to enhance readability

Is there a way to adjust the line height between li tags? I attempted using height:100%, but it seems ineffective. Are my methods correct? Can anyone provide guidance? The following is the code snippet in question: <html xmlns="http://www.w3.org/1999 ...

Creating a Vue Directive in the form of an ES6 class: A step-by-step

Is it possible to make a Vue directive as an ES6 Class? I have been attempting to do so, but it doesn't seem to be working correctly. Here is my code snippet: import { DirectiveOptions } from 'vue'; interface WfmCarriageDirectiveModel { ...

Having trouble with creating SQLite tables using JavaScript within a for loop

I have developed a multi-platform app using AngularJS, JavaScript, Phonegap/Cordova, Monaca, and Onsen UI. In order to enable offline usage of the app, I have integrated an SQLite Database to store various data. After conducting some basic tests, I confir ...

How can I stop full-page auto-scroll screenshot extensions from automatically scrolling?

As the owner of a membership website, I'm faced with the challenge of preventing users from easily taking full page screenshots of the valuable text content in my members area. Many browser extensions, such as Fireshot and GoFullPage, enable auto-scro ...

Encountering issues with generating image files using createObjectURL after transitioning to NextJS 13 from version 10

I'm currently working on a website with the following functionality: Client side: making an API call to retrieve an image from a URL Server side: fetching the image data by URL and returning it as an arrayBuffer Client side: extracting the arrayBuffe ...

DataGrid React MUI: Aligning Column Data and Header for "Number" Type

In my React project, I am using MUI. I noticed that when I specify the type of a column as type: "number", both the column header and data align to the right. This issue can be replicated in a simple example taken from the MUI documentation: code ...

What is the best way to cycle through a nested JS object?

I am currently utilizing useState and axios to make an API call, retrieve the response, and pass it to a Component for rendering. const [state,setState] = useState([]); const getCurrData = () => { axios.get('working api endpoint url').then(r ...

Learn how to utilize ng-class to assign an ID selector to HTML elements

In my code, I have an icon that is displayed conditionally using ng-class. I am looking to include ID's for both the HTML elements. <i ng-show="ctrl.data.length > 1" ng-class="{'glyphicon glyphicon-chevron-down': !ctrl.isOpen, ...

How can I connect the Bootstrap-datepicker element with the ng-model in AngularJS?

Below is the html code for the date field : <div class='form-group'> <label>Check out</label> <input type='text' ng-model='checkOut' class='form-control' data-date-format="yyyy-mm-dd" plac ...

An unexpected error occurred while parsing the JSON document: "unexpected token: '{'"

I'm facing an issue where I need to specify a URL in a JavaScript app that retrieves weather data from an API. The URL is constructed using a string and some variables. When I initially wrote the code below, I encountered the error message Missing { b ...

Tips for creating a new tab or window for a text document

Below code demonstrates how to open a new tab and display an image with a .jpg extension. Similarly, I want to be able to open a text document (converted from base64 string) in a new tab if the extension is .txt. success: function(data) { var ...