Steps for closing the menu by clicking on the link

My issue with the menu on the landing page is that it only closes when clicking the cross button. I want it to close when any link from the menu is clicked. I attempted to add code using querySelector, but it only worked for the home link and not the others. Can someone help me figure out what I'm doing wrong?

let
  burger = document.getElementById("burger"),
  nav = document.getElementById("main-nav"),
  a = document.getElementsByClassName(".nav-link");

burger.addEventListener("click", function(e) {
  this.classList.toggle("is-open");
  nav.classList.toggle("is-open");
});

a.addEventListener("click", function(e) {
  burger.classList.toggle("is-open");
  nav.classList.toggle("is-open");
});
body {
  background: #000;
}

.main-nav {
  position: absolute;
  top: 0;
  right: 0;
  left: -18px;
  text-align: center;
  background: #fff;
  opacity: 0;
  z-index: -1;
  visibility: hidden;
  -webkit-transition: .375s;
  transition: .375s;
  height: 100vh;
  margin: 0 !important;
}
/* CSS styling continues... */</questionbody>
<exquestionbody>
<div class="question">
                
<p>My menu closes only when you click on the cross button. But this is not convenient in the landing page. I want it to close when I click on any link from the menu. I tried to add the code myself, but it doesn’t work out for me. I tried adding querySelector, it worked only on the home link. Other links did not close the menu. What am I doing wrong?</p>

<p><div>
<div>
<pre class="lang-js"><code>let
  burger = document.getElementById("burger"),
  nav = document.getElementById("main-nav"),
  a = document.getElementsByClassName(".nav-link");

burger.addEventListener("click", function(e) {
  this.classList.toggle("is-open");
  nav.classList.toggle("is-open");
});

a.addEventListener("click", function(e) {
  burger.classList.toggle("is-open");
  nav.classList.toggle("is-open");
});
body {
  background: #000;
}

.main-nav {
  position: absolute;
  top: 0;
  right: 0;
  left: -18px;
  text-align: center;
  background: #fff;
  opacity: 0;
  z-index: -1;
  visibility: hidden;
  -webkit-transition: .375s;
  transition: .375s;
  height: 100vh;
  margin: 0 !important;
}

.main-nav.is-open {
  opacity: 1;
  z-index: 100;
  visibility: visible;
}

.main-nav::before {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: -15px;
  background: #000;
  transform-origin: 0 0;
  transform: skew(-14deg) translateX(-120%);
  transition: all .275s .1s;
}

.main-nav.is-open::before {
  transform: skew(-14deg) translateX(0);
}

.main-nav ul {
  display: inline-flex;
  flex-direction: column;
  height: 60%;
  align-items: flex-end;
  justify-content: center;
  transform: translateX(-18%) skew(-16deg);
}

.main-nav li {
  display: block;
  margin: .5rem 0;
  text-align: right;
  transform: skew(16deg);
}

.main-nav a {
  opacity: 0;
  transform: translateY(-10px);
}

.main-nav.is-open a {
  opacity: 1;
  transform: translateY(0);
}

.open-main-nav {
  position: absolute;
  top: 15px;
  padding-top: 20px;
  z-index: 1000;
  background: none;
  border: 0;
  cursor: pointer;
}

.open-main-nav:focus {
  outline: none;
}

.burger {
  position: relative;
  display: block;
  width: 28px;
  height: 4px;
  margin: 0 auto;
  background: #fff;
  transform: skew(5deg);
  transition: all .275s;
}

.burger:after,
.burger:before {
  content: '';
  display: block;
  height: 100%;
  background: #fff;
  transition: all .275s;
}

.burger:after {
  transform: translateY(-12px) translateX(-2px) skew(-20deg);
}

.burger:before {
  transform: translateY(-16px) skew(-10deg);
}
<button id="burger" class="navbar-toggler open-main-nav"><span class="burger"></span></button>
<nav class="main-nav" id="main-nav">
  <ul>
    <li><a href="#home" class="nav-link" title="">home</a></li>
    <li><a href="#services" class="nav-link" title="">services</a></li>
    <li><a href="#portfolio" class="nav-link" title="">portfolio</a></li>
    <li><a href="#about" class="nav-link" title="">about</a></li>
    <li><a href="#contacts" class="nav-link" title="">contacts</a></li>
  </ul>
</nav>

Answer №1

  • Utilize Element.querySelector() and Element.querySelectorAll()
  • Given that you have a series of links, go through them using .forEach() to add a click listener to each anchor.

const
  burger = document.querySelector("#burger"), 
  nav = document.querySelector("#main-nav"),  // If there is an existing ID, make use of it.
  a = document.querySelectorAll(".nav-link"); // Ensure appropriate selectors are used!

burger.addEventListener("click", function(e) {
  this.classList.toggle("is-open");
  nav.classList.toggle("is-open");
});

a.forEach(el => el.addEventListener("click", function(e) {
  burger.classList.toggle("is-open");
  nav.classList.toggle("is-open");
}));
body {
  background: #000;
}

.main-nav {
  position: absolute;
  top: 0;
  right: 0;
  left: -18px;
  text-align: center;
  background: #fff;
  opacity: 0;
  z-index: -1;
  visibility: hidden;
  -webkit-transition: .375s;
  transition: .375s;
  height: 100vh;
  margin: 0 !important;
}

.main-nav.is-open {
  opacity: 1;
  z-index: 100;
  visibility: visible;
}

.main-nav::before {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: -15px;
  background: #000;
  transform-origin: 0 0;
  transform: skew(-14deg) translateX(-120%);
  transition: all .275s .1s;
}

.main-nav.is-open::before {
  transform: skew(-14deg) translateX(0);
}

.main-nav ul {
  display: inline-flex;
  flex-direction: column;
  height: 60%;
  align-items: flex-end;
  justify-content: center;
  transform: translateX(-18%) skew(-16deg);
}

.main-nav li {
  display: block;
  margin: .5rem 0;
  text-align: right;
  transform: skew(16deg);
}

.main-nav a {
  opacity: 0;
  transform: translateY(-10px);
}

.main-nav.is-open a {
  opacity: 1;
  transform: translateY(0);
}

.open-main-nav {
  position: absolute;
  top: 15px;
  padding-top: 20px;
  z-index: 1000;
  background: none;
  border: 0;
  cursor: pointer;
}

.open-main-nav:focus {
  outline: none;
}

.burger {
  position: relative;
  display: block;
  width: 28px;
  height: 4px;
  margin: 0 auto;
  background: #fff;
  transform: skew(5deg);
  transition: all .275s;
}

.burger:after,
.burger:before {
  content: '';
  display: block;
  height: 100%;
  background: #fff;
  transition: all .275s;
}

.burger:after {
  transform: translateY(-12px) translateX(-2px) skew(-20deg);
}

.burger:before {
  transform: translateY(-16px) skew(-10deg);
}
<button id="burger" class="navbar-toggler open-main-nav"><span class="burger"></span></button>
<nav class="main-nav" id="main-nav>
  <ul>
    <li><a href="#home" class="nav-link" title="">home</a></li>
    <li><a href="#services" class="nav-link" title="">services</a></li>
    <li><a href="#portfolio" class="nav-link" title="">portfolio</a></li>
    <li><a href="#about" class="nav-link" title="">about</a></li>
    <li><a href="#contacts" class="nav-link" title="">contacts</a></li>
  </ul>
</nav>

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

Loading Web Applications Screen

My web app contains multiple tree views. Upon loading the page, I first see the unordered lists before the styling of the trees is displayed in the DOM after a brief delay. Is there a method to mask the web app with a spinner placed in the center of the s ...

Is it possible to alter the cursor according to the position of the mouse?

Is it possible to change the cursor from default to pointer when the mouse enters the specific rectangle area (50, 50, 100, 100) of the body? The dimensions are in pixels. Instead of defining a separate div and setting the cursor style on it, I'm loo ...

npm ERR! Your operating system has denied the operation

When attempting to install create-react-app globally using 'npm install -g create-react-app', an error occurred due to insufficient write access to the /usr/local/lib/node_modules directory. The error message displayed was as follows ...

Importing JS files or SDKs in Angular that are not modules

Currently, I am incorporating the Avaya SDK (which consists of 3 JS files) into my Angular project. However, when attempting to import it, I encounter an error stating that it is not recognized as a module. Any suggestions on how to resolve this issue? Th ...

vuejs mounted: Unable to assign a value to an undefined variable

When I try to run the function below upon mounted, I encounter an error: "Cannot set the property 'days' of undefined" Here is my code snippet: function getDays(date) { this.days = (new Date()).getTime() / ...

ReferenceError: source is not defined in Gulp with Browserify

I encountered a strange error while working on my project. The error message I received is as follows: $ gulp browserify [01:21:03] Using gulpfile F:\CSC Assignments\FinalProject\HotelProject\gulpfile.js [01:21:03] Starting 'bro ...

"Unsuccessful jSON request made by Ajax resulting in undefined response

I've implemented an ajax call to fetch data from a json file and display it in an HTML table. Everything was working fine initially, but now it seems to be returning UNDEFINED. Could it be that the data from the json file hasn't finished loading ...

Position the <a> to the right side of the div

Is there a way to right-align the <a> element, which contains a Button with the text Push Me, within the <div> (<Paper>)? https://codesandbox.io/s/eager-noyce-j356qe This scenario is found in the demo.tsx file. Keep in mind that using ...

Can you explain the distinction between angular input and native HTML attributes when used with HTML tags?

Take the input tag as an example, where you have two options to specify a maximum length: <input [maxLength]="20" type="text"> <input maxLength="20" type="text"> Are there any real-world distinctions between using one approach over the othe ...

Issues with Linear-Gradient functionality in NativeScript 8 on Android devices

I recently added a linear-gradient to an image in my NativeScript 8 app. Surprisingly, it seems to work perfectly on iOS, but I'm encountering some issues on Android. Despite trying solutions like using -webkit-linear-gradient(), the desired effect is ...

Instructions for adjusting the size of my modal window when the keyboard appears?

While developing a next.js app, I encountered an issue with the chat modal. When the input field is in focus, I want to resize the modal height so that the keyboard popup does not hide the input field. I attempted to modify the DOM but could not get it to ...

Calculate the sum of a column in a table that is dynamically populated

I'm using jQuery to load a table with data: function getSales(customerId, fromDate, toDate){ $.ajax({ type: 'POST', url: 'ajax/sale_pl.php', data:{customer_id:customerId, from_date:fromD ...

Extracting multiline value from a textarea using JavaScript

I'm trying to extract a multiline value from a textarea using JavaScript or jQuery and store it in a cookie. Below is the code snippet I am using: HTML: <textarea id="cont" cols="72" rows="15"> JavaScript: var txt = $('#cont').val( ...

Developing a robust system for managing classnames

I have a question regarding the article I found on Quora about Facebook's CSS class names structure. They mentioned that both Facebook and Google use a build system to convert developer-friendly class names into shorter ones to save bandwidth and crea ...

Conceal the HTTP status code alert in the Chrome developer console

Currently, I have set up a REST API using Express and for authentication, cookies are being utilized. To retrieve user information, I make a GET request to an endpoint that either returns the user info if logged in or a 401 (Unauthorized) status code if no ...

Stop Code Execution || Lock Screen

Is there a way to address the "challenge" I'm facing? I'm an avid gamer who enjoys customizing my game using JavaScript/jQuery with Greasemonkey/Firefox. There are numerous scripts that alter the DOM and input values. In my custom script, I hav ...

Creating diamond-shaped columns and rows in HTML using the Bootstrap framework is a fun and creative way to

Recently, I tackled the challenge of building a website based on a specific design. Within this design, there was a div element that included an image link. Despite my efforts, I found myself at a loss on how to proceed with this task. Here is the snippet ...

Learn how to dynamically change a class name with JavaScript to alter the color of a navbar icon

I have little experience with javascript, but I want to make a change to my navbar icon. Currently, my navbar has a black background with a white navbar icon. As I scroll the page, the navbar background changes to white and the font color changes to black. ...

Is there a way to dynamically adjust height from 0 to 'auto' using @react-spring useTransition?

When utilizing the useTransition hook to incorporate animation into a list element, I encountered an issue where the height of its child elements is not fixed. If I specify {from:{height:0},enter:{height:'auto'}, the animation effect is lost. Is ...

Error: Cannot access the length property of an undefined value in the JEST test

I'm currently working on incorporating jest tests into my project, but I encountered an error when running the test. The issue seems to be related to a missing length method in the code that I am attempting to test. It appears to be originating from s ...