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

retrieve data from an asynchronous request

Utilizing the AWS Service IotData within an AWS Lambda function requires the use of the AWS SDK. When constructing the IotData service, it is necessary to provide an IoT endpoint configuration parameter. To achieve this, another service is utilized to obta ...

What is preventing SVG textPath from displaying properly? [Empty output in devtools]

I found this interesting code snippet on Mozilla and decided to incorporate it into a Vue component. <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <path id="MyPath" fill="none" stroke="red" d="M10,90 Q90,90 90,45 Q90,10 ...

Is a referrer included in AJAX requests made from the background page of a Google Chrome Extension?

Can anyone confirm if AJAX requests sent from the background page of my Chrome Extension will include referrer information? I'm wondering about this. Appreciate any insights you can provide! ...

Utilizing the Bing Translation API to translate an entire webpage

I am currently attempting to use the Bing API to translate an entire webpage instead of using the Bing widget. This is because I want to create a custom design for the translation panel, However, I have been unable to find any resources on how to do this ...

Iframes are not compatible with JQuery UI dialogs

After attempting to open a URL within an Iframe in a JQuery dialog box, I encountered the following issue: Here is the code snippet that I used: http://pastebin.com/Wqf0mGhZ I am looking for a solution to make sure that the dialog displays all of the con ...

The domain retrieval is contingent on the language preference of the user

A task has been assigned to create a script in JavaScript/jQuery (or other suitable technologies) that will return a domain with a .pl extension if the user's browser language is set to Polish. Otherwise, the script should return a .eu domain extensio ...

Is there a way to assign multiple paths to a single page within the NextJS pages directory?

I'm currently working on a project that has two different themes, and I have the ability to switch between them based on the environment. Everything works perfectly, but I'm encountering an issue with paths. Some pages should open with different ...

Opera browser having trouble with sidebar rendering

On my best days, I struggle immensely with troubleshooting browser display issues. The left-hand sidebar on this page () appears incorrect in Opera. While in all other browsers, the sidebar displays with an orange and tan background, for some unknown reas ...

Utilizing Highcharts/Highstock for handling large volumes of data efficiently

Dealing with a growing amount of data daily (currently over 200k MySQL rows in one week), the chart loading speed has become quite slow. It seems like using async loading is the solution (). I attempted to implement it but encountered some issues. Currentl ...

Encountered an issue while trying to reset the dropdown menu values on a Dash application when utilizing a clear button

I'm attempting to add a clear button for users to reset the values in a dropdown menu. However, when I run the application, I encounter the following error preventing me from selecting an option in the dropdown: Unable to access property 'leng ...

How to Properly Implement app.use() in Express for Middleware

What is the reason behind some middleware functions being passed in with invocation parentheses, while an anonymous function is passed in without being invoked? app.use(logger()); app.use(bodyParser()); If logger() is evaluated immediately and the return ...

The puzzle of Media Queries

I have been searching far and wide for a solution to my issue, which I believe is quite basic. Currently, I am struggling with it mentally. I am in the process of customizing a responsive template. This is uncharted territory for me when it comes to medi ...

Trouble with passing the function variable to setState efficiently

Although I haven't worked with React for a while, it seems like this issue is more related to plain JS. Here is the setState function that I am using: // click event on parent for performance reasons ``Component:`` const [active, setActive] = useSta ...

Is it possible to retrieve JSON data from an external URL using JavaScript or jQuery?

My goal is to retrieve JSON data from the following URL: I have a button that triggers the function called "jsonplz()", which should display an alert message with the fetched JSON data. This is what my JavaScript code looks like: <script src="htt ...

Issue with Heroku deployment: unable to locate JavaScript file

I encountered an issue while deploying my node.js app. Everything seemed to be working fine but it couldn't locate the JavaScript files. The error message displayed was: proove.herokuapp.com/:16 GET 404 (Not Found) Here is the server.js code snip ...

What is the method for adjusting the position of materialize CSS select options?

https://i.stack.imgur.com/b9p9T.png One issue arises when I open the Materialize CSS select, as the options end up covering the input. Ideally, I prefer the options to appear underneath the input. <div class="input-field "> ...

A guide on invoking a function within a nested or local function

When the code below is executed in a local function, such as the one inside s3.getObject, it throws an error stating that setState is not a function. s3.getObject({ Bucket: bucket, Key: key }, function (error, data) { if (error != ...

"Using jQuery's animate() function to dynamically change text content

I'm currently venturing into the world of jQuery animate() and decided to create a presentation-style project for practice. However, I've hit a roadblock when attempting to alter the text within my div element in the midst of an animation utilizi ...

When attempting to set a dynamic src tag for embedding a Google Map in a React application, an X-Frame-Options

I'm attempting to display a specific location using an iframe embed from Google Maps (shown below): <iframe width="100%" height="200" frameBorder="0" scrolling="no" marginHeight={0} marginWidth={0} id="g ...

Array logging mistakenly outputs a number

I needed to access the data from JSON outside of the xml function so that I could use it in multiple functions. When I initially logged the data, it displayed arrays with objects in it. However, when I checked the length instead, it returned zero. After re ...