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

How to save the value of `this.$route.params.id` in a Vue.js data property?

I am currently working with Vue.js 3 and have a sample code for routing and passing parameters. Below is the Home.vue page: <template>   <div class="home">     <h1>       All Destinations     </h1>     < ...

What are the best methods for creating genuinely random and highly secure session IDs?

I am looking to develop session middleware for Express, however, I am unsure about generating random and secure session IDs. How do larger frameworks like Django and Flask handle this issue? What would be the best approach for me to take? ...

Tips for accessing every "results" (parameters) from an API

Here is the response I received after making an API call in my attempt to retrieve each "bloc" result using a .forEach. const app = express(); const axios = require('axios') jobList = []; app.get('/getAPIResponse', function(req, res) ...

Generate visual content using JSON data

I'm in need of assistance with generating a set of images through JSON in ASP .NET MVC4. Is this achievable? The code I am working with is shown below, and I am unsure how to incorporate this functionality. Thank you in advance for any help! [Acce ...

An alternative way to adjust font size without having control over the HTML code

Is there a way to adjust the font size in a web page when only the div or iFrame is editable, not the actual HTML content? Our website allows users to upload their own ebooks, resulting in uncontrolled and complex HTML content for each chapter. We want to ...

Creating animations with an svg mask can be effective, however, it seems to only work properly

I have been experimenting with creating a transition effect using SVG masks and CSS. Initially, everything was working as intended, but after a few repetitions (usually 1 or 2, unpredictably), the transition effect would suddenly stop and become instantane ...

How can I effectively update Bootstrap 4 in a Rails environment?

After attempting to update my Rails 5 project from Bootstrap 4 Alpha 6 to the final version 4.0.0, I confirmed that the v4.0.0 gem was installed (with the alpha version gem uninstalled). However, upon running my project in development mode, I discovered th ...

I am unable to determine if I have already selected a List Item

My goal is to have a functionality where clicking on "Download Drivers" will open the list, and clicking again will close it. This should be achieved with onclick events only, no hover effects. Additionally, I want the list to remain open even if I click o ...

Laying Out Content with Bootstrap4 Grid System and Nesting Rows

design Is it possible to utilize Bootstrap 4's grid system to replicate the layout shown in this image? Can rows be nested within a main row? I've been struggling to achieve this. ...

React.js issue with onChange event on <input> element freezing

I am experiencing an issue where the input box only allows me to type one letter at a time before getting stuck in its original position. This behavior is confusing to me as the code works fine in another project of mine. const [name, setName] = useStat ...

designing a button layout with bootstrap framework

I am attempting to position a "Redigera" button after the "Avsluta" button <div class="row"> <div class="col-md-4"> </div> <div class="col-md-4"></div> <div class="col-md-4"> <button class=" ...

Finding the scope of dynamically generated fields in AngularJS has proven to be quite challenging

I'm currently working on creating a dynamic form where users can add input fields by clicking a button. However, I am facing issues with fetching the value of the input field in the controller. Below is my form: <div ng-repeat="skill in skill_set" ...

The <ul> tag is not receiving the correct styles and is not displaying properly

I have successfully integrated an input control and button into my table within the Angular 7 application. When a user inputs text in the control and clicks the add button, the text is appended to the <ul> list. However, the layout of the <ul> ...

Splicing using only one parameter will make changes to the array without deleting the entire array

let myArray = ['a','b','c','d','e']; console.log(myArray.splice(1)); console.log(myArray); Looking at the splice documentation, it mentions that not providing a delete parameter would remove all array item ...

Conceal the div once it reaches the top of the webpage

Is there a way to hide an "h1" element when its parent div reaches the top of the page and then show it again when it moves down using both JQuery and CSS? I attempted to utilize a scroll listener in JQuery to toggle a class, but this resulted in the "h1" ...

Selecting dates based on week number

Is there a method in asp.net or via javascript to capture the dates (Monday to Friday) when a user clicks on the week number displayed on the calendar and display them on a label? ...

Bootstrap for Twitter: How to Customize Text in the Navigation Bar

As per the twitter bootstrap guidelines, I am supposed to enclose text in a <p> tag for correct leading and color. However, when I try to do this within the navbar element or any of its sub-levels, the text does not inherit any of the styling propert ...

Leveraging server-sent events (SSE) for real-time updates on a web client using JavaScript

I have been experimenting with server-side events (SSE) in JavaScript and Node.JS to send updates to a web client. To simplify things, I created a function that generates the current time every second: setTimeout(function time() { sendEvent('time&a ...

css overflowing content can disrupt the layout of the screen

I am currently working on creating a modal that will be displayed in the center of the screen with the same width as the main page. However, I am facing an issue where the modal is not perfectly centered. I suspect that this is due to the overflow style ...

What is the proper way to call document methods, like getElementByID, in a tsx file?

I am currently in the process of converting plain JavaScript files to TypeScript within a React application. However, I am facing an error with document when using methods like document.getElementById("login-username"). Can you guide me on how to referen ...