I am unable to close the hamburger menu by clicking on it

I am facing an issue with the hamburger icon functionality. The menu opens when I click on it, but it is not getting closed when clicked again. I have been trying to debug the code, but I can't figure out what's causing the problem. If anyone has any insights or solutions, please help.

// Hamberger menu
const navSearch =  document.querySelector('.nav-search');
const navLeft = document.querySelector('.nav-left');
document.querySelector('.toggle').addEventListener('click', () => {
  console.log(navSearch.style.display);
  console.log('1');
  if(navSearch.style.display = "none") {
    console.log('2');
    navSearch.style.display = "inline-block";
    navLeft.style.display = "inline-block";
    console.log(navSearch.style.display);
  } else if(navSearch.style.display = "inline-block") {
    console.log('3');
    navSearch.style.display = "none";
    navLeft.style.display = "none";
  }
console.log('......');
});
// Variables
$website-width: 1280px;
$color-main: #4bbf73;
$color-dark: #343a40;
$color-light: #fff;
$color-lightx2: #f7f7f9;

//General Styles
* {
  margin: 0;
  padding: 0;
}

body {
  background-color: $color-light;
  font-family: "Nunito", Arial, Helvetica, sans-serif;
  line-height: 1.6;
}

a {
  text-decoration: none;
  color: $color-light;
}

ul {
  list-style: none;
}

h2,
h3,
h4 {
  text-transform: uppercase;
}

img {
  width: 100%;
}

input {
  border: none;
  padding: 0.7rem 1rem;
  background: $color-lightx2;

  &:focus {
    outline: none;
  }
}

// Utilities
.container {
  max-width: $website-width;
  padding: 0 1.5rem;
  margin: auto;
  overflow: hidden;
}

// navbar
header {
  background: $color-dark;
  height: 100px;

  #navbar {
    padding-top: 1.3rem;
    color: $color-light;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;

    .nav-logo {
      font-size: 1.5rem;
      font-weight: 900;
      letter-spacing: 2px;
      padding: 0.5rem 1rem;
    }

    ul {
      display: flex;
      justify-content: center;

      li {
        padding-left: 1.5rem;
      }
    }

    input[type="submit"] {
      margin-left: 0.4rem;
      background-color: inherit;
      border: $color-main 2px solid;
      color: $color-main;

      &:hover {
      
        background-color: $color-main;
        color: $color-light;
        transition: all 0.2s ease-in-out;
      }
    }

    input[type="text"] {
      padding: 0.7rem 1rem;
    }
  }

  .toggle {
    position: absolute;
    top: 2.2rem;
    right: 6rem;
    transform: scale(2);
    display: none;
  }
}

@import 'media';

@media (max-width: 850px) {
  header {
    height: auto;

    #navbar {
      flex-direction: column;
      align-items: start;

      input[type="text"] {
        margin: 1rem 0 1.4rem 3rem;
      }

      ul {
        padding-bottom: 1rem;
      }
    }

    .toggle {
      display: inline-block;
    }

    .nav-search,
    .nav-left {
      display: none;
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.0/css/all.css"
    integrity="sha384-OLYO0LymqQ+uHXELyx93kblK5YIS3B2ZfLGBmsJaUyor7CpMTBsahDHByqSuWW+q" crossorigin="anonymous">
  <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@300&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="scss/style.css">
  <title>AllMart</title>
</head>
<body>
  <header>
    <div class="container">
      <nav id="navbar">
        <div class="nav-logo">
          <a href="index.html">AllMart</a>
        </div>
        <div class="nav-search">
          <form>
            <input type="text" placeholder="Search Product...">
            <input type="submit" value="SEARCH">
          </form>
        </div>
        <div class="nav-left">
          <ul>
            <li id="cart"><a href="#"><i class="fas fa-shopping-cart"></i> CART</a></li>
            <li id="profile"><a href="#"><i class="fas fa-user"></i> SIGN IN</a></li>
          </ul>
        </div>
      </nav>
      <span class="toggle"><a href="#"><i class="fas fa-bars"></i></a></span>
    </div>
  </header>
  <script src="js/index.js"></script>
</body>
</html>

On clicking the icon, this is the output that I get:

https://i.sstatic.net/zvAUE.png

I would greatly appreciate any assistance in identifying and resolving the issue. Thank you!

Answer №1

When writing conditional statements in JavaScript, always remember to use === or == instead of = to compare values. Using = is an assignment operator and not a comparison operator. It's recommended to use === for strict equality testing without any type conversion.

if(navSearch.style.display === "none") {

} else if(navSearch.style.display === "inline-block") {

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

Using @at-root seems to be causing an error when combining the "a" selector with

I encountered an issue when attempting to use @at-root and Interpolation in my Sass code. Despite using a standard example for testing, I still receive an error: .button { @at-root a#{&} { color: green; } } Error sass/Site.scss (Line 28 of s ...

Menu items on the responsive design are vanishing

I am facing an issue with my sample menu layout. It appears fine on desktop view, but when I switch to a smaller window size of 480px, the items from About to Contact disappear when I hover away from the last item in the .has-children class. It seems like ...

Incorporating JSON data into data-groups within an Ionic application

I am currently working on developing an Ionic app using the newest version (Ionic 3xx and Angular 5) and I am attempting to incorporate the shuffleJS feature for filtering. Everything was working fine when I used static data in my template with the 'd ...

Invoke a function within a JavaScript file from a separate file by utilizing a setTimeout method, all while incorporating the power of Angular

I've encountered an issue with my barcode scan detection code. Originally, the code was working fine when it was placed directly in an AngularJS controller. However, I needed to use the same code in another controller as well, so I moved the scan code ...

Calculate and retrieve the result from the event handling function

I need to capture a returned value and store it in a variable within an event handler function. Below is a sample code snippet demonstrating this: var xhr = new XMLHttpRequest(); function getData(e) { if (xhr.readyState === 4) { if (xhr.s ...

The pre-loader is hidden behind the block content and navigation bar

I've encountered an issue with my preloader where it's loading in front of the <body> element but not in front of the site's <navbar> or the {% block content %}. The CSS snippet to increase the z-index of the preloader is as foll ...

Having difficulty adjusting the appearance of the navigation bar dropdown

I'm currently facing an issue with changing the background color of my nav-bar dropdown to black, as well as adjusting the width of the dropdown options to fit the screen. Despite trying the code provided below, I am unable to change the dropdown bac ...

AngularJS does not bind redefined variables

Having just started delving into Angular, I've encountered an issue while creating an application where a single AngularJS bind fails to update when the value of the bound object changes. This is a simplified version of the app, hence its structure. ...

Guide on looping through a collection of objects that have child objects and generating a new custom object

I am currently working with an object list retrieved from an API. The response looks something like this: { "1/22/20": { "new_daily_deaths": 0, "total_cases": 1, }, "1/23/20": { "new_deaths": 0 ...

Using an if statement condition within an ng-repeat in AngularJS

I am currently utilizing the ng-repeat feature in AngularJS <ul> <li ng-repeat="question in questions" class="question list-group-item media"> <span class="question__type">{{ question.question }}</span> <br&g ...

Refreshing data causes the data to accumulate and duplicate using the .append function in Jquery

I am currently working with a dynamic table that is being populated using AJAX and jQuery. Everything seems to be functioning correctly, however, I am encountering an issue when trying to reload the data as it just continues to stack up. Below is the func ...

Collapse all Bootstrap accordions with a single click of a button

Is there a simple way to toggle the collapse/expand functionality of all accordions with just one button click? I attempted to achieve this by using a basic button that would remove the 'active' class and add it back, but unfortunately, it didn&a ...

Find the final element that does not include a particular class

Looking for the best way to identify the last item in a list without a specific class? Learn how to write code that can check for the absence of a class name. $('ul li:last') $('ul li:not(.special)') ...

Chrome by Google is experiencing issues with displaying stylesheets

Here is a script I have been using: <?PHP $Document = $_GET["Name"]; Switch($Document) { Default: Echo "Incorrect document name! Please check if it exists."; Exit; Case "Style": $Document = "Folder/Styles/MainS ...

Restricting the input on a React component to only accept alphabet characters from A to Z instead of allowing any keyboard

I am currently facing a challenge with understanding a specific component, particularly the allowForClassification value. This boolean value is passed down to a child component and decides whether a button is displayed or not. The issue arises when tryin ...

How are resolve and reject utilized within JavaScript Promises?

Initially, I believed that resolve simply passes the parameter to the function in then, so I conducted this experiment: const promise = new Promise((resolve, reject) => { resolve(new Promise(resolve => resolve(2333))) }) // promise.then(innerPromi ...

Fetching database entries upon page load instead of using the keyup function in JavaScript

Here is an HTML form input provided: <input type="text" id="username" value=""> In this scenario, when a username like "John" is entered and the enter button is pressed, the script below retrieves database records: $(function(){ //var socket = ...

Detecting if the request in Yii Framework 2.0 is coming from an AJAX GET call

While utilizing Yii framework 2.0, I have implemented an AJAX GET jQuery script that references a function within a controller class. $.get('localhost/website/index', {param: 'xxxx'}, function(returnedData){ // some code here..... ...

Vue alert: Issue encountered in watcher 'childItems' callback - 'TypeError: Unable to access property 'tag' as it is undefined'

I am currently in the process of developing the Store page for a web application. I am utilizing Axios to retrieve product data and display it in a Vue template. While the backend functionality is working correctly and the frontend is rendering successfull ...

button that decreases in size when clicked on

Currently, I am dealing with an element that functions as a button using a combination of Javascript and CSS. To better illustrate the issue, I will simplify the example by removing unnecessary details. The main problem lies in the fact that when this elem ...