What could be causing my toggle button to not trigger my responsive menu in JavaScript?

How can I make the navigation menu open when clicking the hamburger menu in the first list item? I tried using JavaScript to target the `nav-list` class in the second list item, but nothing happens on click.

Initially, I had the hamburger icon and links in one list and attempted to use `display: none` for everything except the first list item. However, I ran into issues with getting `getElementsByClassName` to display the rest of the list items upon click event.

const toggleButton = document.getElementsByClassName('toggle-button')[0]
const navList = document.getElementsByClassName('nav-list')[0]

toggleButton.addEventListener('click', () => {
  navList.classList.toggle('active')
})
/* Nav Styling */

.navbar-links ul {
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: space-around;
  font-weight: 600;
  font-size: 18px;
}

.navbar-links li {
  list-style-type: none;
}

.navbar-links li a {
  text-decoration: none;
  color: whitesmoke;
  padding: 1rem;
  display: block;
}

.navbar-links li:hover {
  background-color: #555;
}

.nav-icon li {
  display: none;
}


/* When menu icon clicked, javascript shows nav items */

@media screen and (max-width: 740px) {
  /* Responsive Navbar */
  .nav-icon li {
    display: block;
  }
  .nav-list li {
    display: none;
  }
  .nav-list ul {
    flex-direction: column;
    width: 100%;
  }
  .nav-list li {
    text-align: center;
  }
  .nav-list li a {
    padding: .5 rem 1 rem;
  }
  /* For Javascript */
  .nav-list.active {
    display: flex;
    flex-direction: column;
  }
}
<nav class="navbar">
  <div class="navbar-links">
    <ul class="nav-icon" id="nav-icon">
      <li>
        <a href="#" class="toggle-button">
          <i class="fa fa-bars"></i>
        </a>
      </li>
    </ul>
    <ul class="nav-list">
      <li><a href="index.html">HOME</a></li>
      <li><a href="activities.html">SELF-HELP TOOLS</a></li>
      <li><a href="conditions.html">CONDITIONS</a></li>
      <li><a href="resources.html">RESOURCES</a></li>
      <li>
        <a href="contacts.html">CONTACT</a>
      </li>
    </ul>
  </div>
</nav>

Answer №1

Are you looking for this specific functionality: When the menu icon (denoted here as A) is clicked, the list configuration changes from a row layout to a column layout upon subsequent clicks.

In order to achieve this, you need to apply display: none not on the nav-list li, but on the nav-list itself within your JavaScript function. The function currently toggles the class active on the nav-list, so make sure your CSS aligns with this logic.

The decision lies with you whether to adjust the CSS or modify the JavaScript function accordingly.

const toggleButton = document.getElementsByClassName('toggle-button')[0]
const navList = document.getElementsByClassName('nav-list')[0]

toggleButton.addEventListener('click', () => {
  navList.classList.toggle('active')
})
/* Nav Styling */

.navbar-links ul {
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: space-around;
  font-weight: 600;
  font-size: 18px;
}

.navbar-links li {
  list-style-type: none;
}

.navbar-links li a {
  text-decoration: none;
  color: lightblue;
  padding: 1rem;
  display: block;
}

.navbar-links li:hover {
  background-color: #555;
}

.nav-icon li {
  display: none;
}


/* Display nav items when menu icon is clicked using Javascript */

@media screen and (max-width: 740px) {
  /* Responsive Navbar */
  .nav-icon li {
    display: block;
  }
  .nav-list {
    display: none;
  }
  .nav-list ul {
    flex-direction: column;
    width: 100%;
  }
  .nav-list li {
    text-align: center;
  }
  .nav-list li a {
    padding: .5 rem 1 rem;
  }
  /* For Javascript */
  .nav-list.active {
    display: flex;
    flex-direction: column;
  }
}
<nav class="navbar">
  <div class="navbar-links">
    <ul class="nav-icon" id="nav-icon">
      <li>
        <a href="#" class="toggle-button">
          <i class="fa fa-bars">A</i>
        </a>
      </li>
    </ul>
    <ul class="nav-list">
      <li><a href="index.html">HOME</a></li>
      <li><a href="activities.html">SELF-HELP TOOLS</a></li>
      <li><a href="conditions.html">CONDITIONS</a></li>
      <li><a href="resources.html">RESOURCES</a></li>
      <li>
        <a href="contacts.html">CONTACT</a>
      </li>
    </ul>
  </div>
</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

Creating consistent column widths in CSS tables

Is it possible to create a table where all columns have equal width, without setting a specific overall table width or specifying individual column widths? In simpler terms, can we make each column automatically adjust to the width of the widest column, w ...

Setting up WebPack for TypeScript with import functionality

A tutorial on webpack configuration for typescript typically demonstrates the following: const path = require('path'); module.exports = { ... } Is it more advantageous to utilize ES modules and configure it with import statements instead? Or is ...

Preventing Event Loop Blocking in Node.js: The Key to Streamlining Performance

I am currently working on developing two APIs using Express.js. The tasks for both APIs are quite straightforward. The first API involves running a for loop from 1 to 3,000,000, while the second API simply prints a string in the console. All the necessary ...

Vanishing essence

http://jsfiddle.net/ddGHz/1004/ //html <div id = "anglereturn"/> <div class="box"></div> //js, jquery var box=$(".box"); var boxCenter=[box.offset().left+box.width()/2, box.offset().top+box.height()/2]; $(document).mousemove(function ...

Traversing through asp:GridView information with javascript

Is it possible to iterate through the data in an asp:GridView on the Client-side using JavaScript? If so, I would like to understand how this can be achieved... My objective is to extract the values of two fields in the Grid and add an image to each row b ...

Provide props to vue-router along with boostrap-vue's b-nav-item

I am currently in the process of transitioning my SPA from modals that load components to routed pages that load components. I have been able to successfully open a page using to="/fixtures" in the html, but I am facing an issue with passing in a component ...

React, incorporating emojis within a dropdown menu

Recently, I've been developing a small game using React where players can customize settings before beginning. The game involves four players chasing different tokens on the map while avoiding the player designated as "it". Within my code, I have a r ...

The Resharper guideline "Function Parameter" doesn't allow the usage of AngularJS service names

I have a question regarding naming conventions in my AngularJS app. Currently, all my service names start with an uppercase character. However, I am facing an issue where service parameters must match the service name, but Resharper's JavaScript "Func ...

Does the ThreeJS Bloom Example provide the desired outcome when copied line by line?

Comparing the results of my bloom filter with an online example reveals some discrepancies. Online Example: https://i.sstatic.net/l7hOtm.png My Output: https://i.sstatic.net/vc7ytm.png Although I have copied the example code exactly, my output does no ...

The analytics dashboard is not displaying the user_timing Google Analytics data, even though it was successfully triggered on the website

I am currently working with Angular and utilizing the navigation_start and end events in app.component.ts to measure the timing before firing a simple page_view and timing event. Both sets of data are then sent to analytics through the network tab. The cod ...

The curious case of Jade view caching in Express

Recently, I updated my Node.js and Express to versions 0.10.21 and 3.4.4, respectively, and now I'm encountering some strange view caching issues during development (as well as production). It appears that the HTML generated from views included withi ...

What is the best way to check if a function has been successfully executed?

When working with PDF documents, I often use an instance of pdfkit document known as doc: import PDFDocument from 'pdfkit' const doc = new PDFDocument() This doc instance is then passed into a function called outputTitle: export const outputTi ...

How to eliminate the inner padding border within a Material UI Outlined Text Field

I am currently utilizing the Material UI v5 Outlined TextField component to develop a form. In the image below, you can see a white padding border appearing in the TextField. I have created CSS that changes the input field color to yellow when focused. Th ...

Is it feasible to exclusively apply Twitter Bootstraps .navbar-fix-to-top on mobile devices?

I am working on a website using Twitter Bootstrap 3 and I have implemented the following navbar: <div class="col-xs-12 col-md-10 col-md-offset-1"> <nav class="navbar navbar-inverse" role="navigation"> <div class="navbar-header"> ...

What is the best way to determine the number of lines within a textarea?

My goal is to accurately calculate the number of lines in a textarea, like so: line 1 line 2 line 3 line 4 which should equal 4 lines. Essentially, pressing enter once should create a new line. Unfortunately, the following code is not achieving this: v ...

Decrease the distance between hyperlinks

I understand that this question has been asked numerous times before, but as a beginner in HTML, I still require some assistance. Given the code provided below, how can I decrease the spacing between the links in each column? Code: a { color: white; ...

It is not possible to make a call to Response.Redirect from within a static method

Hello, I am attempting to execute a webmethod using ajax from an aspx page. Essentially, I would like to redirect to another aspx page with a query string, but I need to do it through <a href> because it is part of a jQuery menu. Based on my underst ...

"Enhance your HTML table by selecting and copying cell values with a simple click and CTRL +

I stumbled upon a fantastic script for highlighting HTML table rows and it's working perfectly: I decided to modify the onclick event to onmouseover and included additional code to select a cell by clicking on it. Now I can select, check which one is ...

When a required field is empty or an alert modal for incorrect input appears, the login inside the dropdown will automatically close

Currently, I am facing an issue with a login form enclosed within a Bootstrap 4 dropdown. Whenever I click on the dropdown, it pops up as expected. The problem arises when a field in the form is required and there is no message displayed upon closure (HTM ...

A concise way to write an else if statement in Javascript and jQuery

Is there a way to make this code more concise? It works perfectly fine, but it's too lengthy. Basically, the code involves two dropdown lists where the user selects options, and based on their selection, values appear in two textboxes. The catch is th ...