The navigation menu refuses to close even after pressing the button

I have been following a tutorial on creating a scroll reveal website, but I've encountered an issue where my navigation menu won't close. Even though I copied the exact same code from the video/documentation. The idea is that when I click a JavaScript button, it should close the nav and then open it again.

I would really appreciate some assistance.

/*=============== SHOW MENU ===============*/
const navMenu = document.getElementById('nav-menu'),
      navToggle = document.getElementById('nav-toggle'),
      navClose = document.getElementById('nav-close')

/*===== MENU SHOW =====*/
/* Validate if constant exists */
if(navToggle){
    navToggle.addEventListener('click', () => {
        navMenu.classList.add('show-menu')
    })
}

/*===== MENU HIDDEN =====*/
/* Validate if constant exists */
if(navClose){
    navClose.addEventListener('click', () => {
        navMenu.classList.remove('show-menu')
    })
}

/*=============== REMOVE MENU MOBILE ===============*/
const navLink = document.querySelectorAll('.nav__link')

const linkAction = () => {
    const navMenu = document.getElementById('nav-menu')
    
    // When we click on each nav__link, we remove the show-menu class
    navMenu.classList.remove('show-menu')
}
navLink.forEach(n => n.addEventListener('click', linkAction))

// Additional JavaScript functions commented out for brevity

It seems that despite copying over the code accurately, the close button is not functioning as expected, and the menu remains visible. Additionally, the placement of the four dots icon seems to be incorrect within the navigation menu. Any guidance or support provided would be highly valued.

An extensive HTML/CSS/JavaScript code has been included in this post per your request. Please note that the project is still a work in progress.

Answer №1

Indeed, the solution does work effectively. Upon examining your CSS code closely, you'll notice that a Media Query is utilized to position the .nav__menu element off-screen. This Media Query specifically targets screens with a maximum width of 767px, ensuring that the styling only applies within this range. By adjusting your screen size, you'll observe that the hamburger menu smoothly disappears and becomes functional when toggling the button!

@media screen and (max-width: 767px){
  .nav__menu{
    position: fixed;
    top: -100%;
    left: 0;
    background-color: var(--body-color);
    width: 100%;
    box-shadow: 0 8px 20px hsla(19, 64%, 24%, .1);
    padding-block: 3.5rem;
    transition: top .4s;
  }
}

Answer №2

To implement the toggle function in JavaScript, make sure to add the following code snippet:

/*=============== TOGGLE FUNCTION ===============*/
const toggleButton = document.getElementById('toggle-button');

if(toggleButton){
    toggleButton.addEventListener('click', () => {
         const elements = document.querySelectorAll('.element');
  
  elements.forEach(element => element.classList.toggle('active'));
      // Additional action here
    })
}

Additionally, you can modify the CSS code for styling purposes:

/*=============== CUSTOM STYLES ===============*/
.element {
  background-color: lightblue;
  padding: 1rem;
  border: 2px solid blue;
  display: flex;
  justify-content: center;
  align-items: center;
}

.active {
  background-color: lightgreen;
}

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

Is there a way to create a hover effect on an input number field within a certain class, causing the -webkit-inner-spin-button opacity to change to 1?

Is it possible to achieve this? I attempted the following, but it's not working: .myClass input[type=range]:hover > .myClass input[type=range]::-webkit-inner-spin-button{ opacity: 0; } .myClass input[type=range]:hover > input[type=range]:: ...

Expanding the link directory

I am struggling with accessing the "file.php" in the "folder1" directory from the "site" directory. The href path I'm using is: href = "folder1/file.php" However, it redirects me to: href = "folder1/folder1/file.php" Additionally, when try ...

Remove the active class after it has been clicked for the second time

Currently, I am working on a menu/submenu system where I want to toggle active classes when clicked. However, I encountered an issue - if the same menu item is clicked twice, I need to remove the active class. Initially, I tried using jQuery's toggleC ...

Create an angle-div element that can be expanded or collapsed without relying on

I'm currently experimenting with creating a diagonal div that adjusts its height based on the content within it. While I can extract height values using JavaScript, I am curious if achieving this effect is possible exclusively through CSS. Thus far, ...

Checkbox inputs with activated labels causing double events to fire

Creating round checkboxes with tick marks dynamically and appending them to id="demo" on the click of two buttons that invoke the get(data) method is my current goal. The issue arises when both buttons are clicked simultaneously, as the checkboxes do not ...

Is there a way to determine if the validityMessage is currently being displayed on a DOM element using reportValidity()?

When reportValidity() is called on an invalid field, the validation message is displayed in a manner that varies depending on the browser. However, if reportValidity() is called again, the validation message disappears on Safari but not on Firefox. Contin ...

The function of cookieParser() is causing confusion

Having an issue that I've been searching for answers to without success. When using app.use(express.cookieParser('Secret'));, how can we ensure that the 'Secret' is truly kept secret? I'm feeling a bit lost on this topic. Is ...

Avoiding JavaScript onclick event using JSON information

Here's a situation I'm dealing with: I have a button created using PHP that triggers a JavaScript onclick event: <button onClick='edit(this, "<?php echo $this->result[$i]["type"]; ?>","<?php echo $quality; ?>", "<?php e ...

What could be causing the issue with my Date and Time input not functioning correctly?

I developed a React frontend application styled with Material UI design. The issue I am facing is that after adding the Date and Time component styling to the form, it is unable to process the "name" value for posting. Specifically, the error message "Ty ...

Tips for dynamically changing the number of visible ListItems in React using a single method

I recently stumbled upon the perfect solution at this link using material-ui. The chapter on "Nested list items" caught my attention, as it only has one nested item with a method for expanding more or less. In my sidebar, I have two nested items that both ...

Sending information from JavaScript to php within a single file

Every time I try to use getDate() in my php file, I notice that the time returned is consistently 5 hours behind the system time. To address this issue, I have implemented a JavaScript solution to retrieve the time from the system instead. Below is the cod ...

What is the Angular approach for configuring a form's encoding type to application/json?

I need to send form data using a POST request that triggers a download, making it impossible to use any Javascript requests. Therefore, calling a function with the $http service is not an option. Additionally, I require the corresponding backend route in ...

The Select2 dropdown does not function correctly within the Bootstrap popover

My concern is about integrating a select2 dropdown into my popover. The issue I am facing is that when I open the popover for the first time, the select2 dropdown renders correctly. However, upon closing and reopening the popover, it displays two select2 d ...

Dealing with rowspan and colspan issues in Internet Explorer

Currently, I am facing the challenge of creating a table with a complex system of colspans and rowspans. If you want to take a look at it, you can view it here This is the HTML code for the table: <table cellspacing="0" cellpadding="0" style="table-la ...

Receiving a redirect when making an AJAX post request in ASP.NET

I am currently working with the Visual Studio 2013 ASP.NET Identity template. Once a user logs in successfully, they are directed to a page containing a table. This page includes search options that are powered by JavaScript. The JavaScript function sends ...

Verify that the data attribute is not blank

I would like to iterate through all the td cells in a table and examine their data attributes. If the attribute contains a value, I want to display it using console.log. Currently, I have the following code but it is not functioning as expected (it merely ...

Creating interactive button groups with responsive design in a Material UI and ReactJS web application

Is it possible to make ButtonGroup Buttons responsive? I heard about an attribute called "Orientation" in material-ui's ButtonGroup, but I'm not sure how to use it with media queries for changing orientation based on the device width. I'm st ...

AWS: Grant access to designated clients for users

My AWS Cognito setup includes: AWS Cognito User Pool: UserPool_1 The User Pool contains 3 users: Mike, Sarah, John I have configured 3 App Clients under this user pool: WebClient_1 WebClient_2 WebClient_3 I need Mike to be able to access: WebClient_ ...

Is there a way to use a button to delete items stored in localStorage?

I am trying to create a button that will clear the local storage for a user using localStorage.clear();, but it is not working as expected. Unfortunately, if you check out the demo, you'll see that it doesn't work properly. Here's the demo ...

Adjusting the height of an IFRAME on the fly

One solution to dynamically fix the height issue of Google Trend charts is by modifying the code output. An example of this can be seen in the code snippet below: <iframe width="600" height="320" src="http://www.google.com/trends/fetchComponent?hl=en-U ...