Pressing the menu button will trigger a function that halts after the third click

As I attempted to implement the functionality of this left menu bar, I encountered a roadblock. The click event on the menu button seems to work fine initially - the left bar appears with the first click and closes as expected with the second click. However, when I attempt to open it again with a third click, the bar fails to appear. I suspect that this issue arises because there is no loop in place, causing it to remain stuck at the last listener. I considered implementing a switch case, but my limited knowledge of JavaScript hinders me. As someone new to coding in JavaScript, any guidance or suggestions would be greatly appreciated.

document.getElementById('menu-ic').addEventListener('click', function(evt) {
document.getElementById('menu-hidden').style.left = '0';
document.getElementById('l1').style.cssText = 'background-color: #000000;width:0px;';
document.getElementById('l2').style.cssText = 'background-color: #000000;width:26px;';
document.getElementById('l3').style.cssText = 'background-color: #000000;width:0px;';
if (document.getElementById('menu-hidden').style.left = '0') {
document.getElementById('menu-ic').addEventListener('click', function(evt) {
document.getElementById('menu-hidden').style.left = '-300px';
document.getElementById('l1').style.cssText = 'width:20px;';
document.getElementById('l2').style.cssText = 'width:24px;';
document.getElementById('l3').style.cssText = 'width:22px;';
});
}
});
#menu-hidden {
  position: absolute;
  width: 300px;
  height: 1200px;
  background: #ffffff;
  /* Old browsers */
  background: -moz-linear-gradient(-45deg, #ffffff 0%, #dbdbdb 37%, #bababa 72%, #dbdbdb 100%);
  /* FF3.6-15 */
  background: -webkit-linear-gradient(-45deg, #ffffff 0%, #dbdbdb 37%, #bababa 72%, #dbdbdb 100%);
  /* Chrome10-25,Safari5.1-6 */
  background: linear-gradient(135deg, #ffffff 0%, #dbdbdb 37%, #bababa 72%, #dbdbdb 100%);
  /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#dbdbdb',GradientType=1 );
  /* IE6-9 fallback on horizontal gradient */
  opacity: 0.98;
  top: -120px;
  left: -300px;
  z-index: 550;
  transition: all 1s ease; }
#menu-hidden ul {
  position: absolute;
  top: 15%; }
#menu-hidden ul li {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 120px;
  float: right;
  list-style: none;
  text-align: right; }
#menu-hidden ul li a {
  font-family: sans-serif;
  color: #2c2c2c;
  font-size: 18px;
  text-transform: uppercase; }
#menu-hidden ul li a:hover {
  color: #d6222f;
  transition: all 0.5s ease; }

button:focus {
  outline: none;
}
nav {
  position: relative;
  display: inline-block;
  float: left; }
#menu-ic {
  background: none;
  border: none;
  position: absolute;
  cursor: pointer;
  width: 30px;
  height: 30px;
  top: 30px;
  left: 30px;
  z-index: 600; }
#menu-ic hr {
  height: 2px;
  background-color: #000;
  position: absolute;
  border: none;
  transition: all 1s ease;
  z-index: 500;
}
#l1 {
  width: 20px;
  top: 0; }
#l2 {
  width: 24px;
  top: 8px; }
#l3 {
  width: 22px;
  top: 16px; }
<div id="menu-hidden" >
  <ul>
    <li><a href="#" class="anchor-scroll active">Retail Registration</a></li>
    <li><a href="#" class="anchor-scroll">Wholesale Registration</a></li>
    <li><a href="#" class="anchor-scroll">Mens Clothing</a></li>
    <li><a href="#" class="anchor-scroll">Women</a></li>
    <li><a href="#" class="anchor-scroll">Private Label</a></li>
    <li><a href="#" class="anchor-scroll">Lookbook</a></li>
    <li><a href="#" class="anchor-scroll">Catalogue</a></li>
    <li><a href="#" class="anchor-scroll">Contact Us</a></li>
  </ul>
</div> 

<nav>
  <button id="menu-ic">
    <hr id="l1">
    <hr id="l2">
    <hr id="l3">
  </button>
</nav>

Answer №1

To prevent nesting click events, you can use a boolean variable to track the state of the sidebar being open or closed. When the menu icon is clicked, the corresponding code will be executed based on the value of this variable:

var opened = false;
document.getElementById('menu-ic').addEventListener('click', function(evt) {
  if (opened == true) {
    document.getElementById('menu-hidden').style.left = '-300px';
    document.getElementById('l1').style.cssText = 'width:20px;';
    document.getElementById('l2').style.cssText = 'width:24px;';
    document.getElementById('l3').style.cssText = 'width:22px;';
    opened = false;
  } else {
    document.getElementById('menu-hidden').style.left = '0';
    document.getElementById('l1').style.cssText = 'background-color: #000000;width:0px;';
    document.getElementById('l2').style.cssText = 'background-color: #000000;width:26px;';
    document.getElementById('l3').style.cssText = 'background-color: #000000;width:0px;';
    opened = true;
  }
});
#menu-hidden {
  position: absolute;
  width: 300px;
  height: 1200px;
  background: #ffffff;
  /* Old browsers */
  background: -moz-linear-gradient(-45deg, #ffffff 0%, #dbdbdb 37%, #bababa 72%, #dbdbdb 100%);
  /* FF3.6-15 */
  background: -webkit-linear-gradient(-45deg, #ffffff 0%, #dbdbdb 37%, #bababa 72%, #dbdbdb 100%);
  /* Chrome10-25,Safari5.1-6 */
  background: linear-gradient(135deg, #ffffff 0%, #dbdbdb 37%, #bababa 72%, #dbdbdb 100%);
  /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#dbdbdb', GradientType=1);
  /* IE6-9 fallback on horizontal gradient */
  opacity: 0.98;
  top: -120px;
  left: -300px;
  z-index: 550;
  transition: all 1s ease;
}
#menu-hidden ul {
  position: absolute;
  top: 15%;
}
#menu-hidden ul li {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 120px;
  float: right;
  list-style: none;
  text-align: right;
}
#menu-hidden ul li a {
  font-family: sans-serif;
  color: #2c2c2c;
  font-size: 18px;
  text-transform: uppercase;
}
#menu-hidden ul li a:hover {
  color: #d6222f;
  transition: all 0.5s ease;
}
button:focus {
  outline: none;
}
nav {
  position: relative;
  display: inline-block;
  float: left;
}
#menu-ic {
  background: none;
  border: none;
  position: absolute;
  cursor: pointer;
  width: 30px;
  height: 30px;
  top: 30px;
  left: 30px;
  z-index: 600;
}
#menu-ic hr {
  height: 2px;
  background-color: #000;
  position: absolute;
  border: none;
  transition: all 1s ease;
  z-index: 500;
}
#l1 {
  width: 20px;
  top: 0;
}
#l2 {
  width: 24px;
  top: 8px;
}
#l3 {
  width: 22px;
  top: 16px;
}
<div id="menu-hidden">
  <ul>
    <li><a href="#" class="anchor-scroll active">Retail Registration</a>
    </li>
    <li><a href="#" class="anchor-scroll">Wholesale Registration</a>
    </li>
    <li><a href="#" class="anchor-scroll">Mens Clothing</a>
    </li>
    <li><a href="#" class="anchor-scroll">Women</a>
    </li>
    <li><a href="#" class="anchor-scroll">Private Label</a>
    </li>
    <li><a href="#" class="anchor-scroll">Lookbook</a>
    </li>
    <li><a href="#" class="anchor-scroll">Catalogue</a>
    </li>
    <li><a href="#" class="anchor-scroll">Contact Us</a>
    </li>
  </ul>
</div>

<nav>
  <button id="menu-ic">
    <hr id="l1">
    <hr id="l2">
    <hr id="l3">
  </button>
</nav>

Answer №2

It appears that the mistake lies in assigning a click event within another click event for various states. A solution would be to define a variable called isHidden

var isHidden = true;
document.getElementById('menu-ic').addEventListener('click', function(evt) {
  if(isHidden){
      document.getElementById('menu-hidden').style.left = '0';
      document.getElementById('l1').style.cssText = 'background-color: #000000;width:0px;';
      document.getElementById('l2').style.cssText = 'background-color: #000000;width:26px;';
      document.getElementById('l3').style.cssText = 'background-color: #000000;width:0px;';
    }else{
                document.getElementById('menu-hidden').style.left = '-300px';
                document.getElementById('l1').style.cssText = 'width:20px;';
                document.getElementById('l2').style.cssText = 'width:24px;';
                document.getElementById('l3').style.cssText = 'width:22px;';

    }
    isHidden = !isHidden
});

View an example on JSFiddle here

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 multiple lines with kineticjs in a HTML5 environment can be a

Referencing the following page: KineticJS - Drawing Lines with Mouse KineticJs is effective in creating lines, shapes, and enabling drag-and-drop functionality. The provided example consistently redraws the same line, prompting the question of how to draw ...

Utilize a jQuery plugin within an AngularJS function

I am using the jQuery plugin select2 and I need to call the select2 function in AngularJS. Although I am aware that I can utilize angular-ui/ui-select, the page design specifically requires the jQuery plugin select2. My goal is to update the value in the ...

Manipulation of CSS DOM elements for achieving responsive design

I am working with a div field that contains an input element and a label element, both set to display:block <div class="cf-full"> <input id="a" > <label class="helptext"></label> </div> In the standard view, the inpu ...

What methods can I use to prevent floated child divs from wrapping?

I'm currently working on creating a carousel-like feature where users can select radio buttons within various div elements. The concept involves having approximately 20 divs, each 150px wide, containing radio buttons. I want to prevent these 20 divs f ...

JQUERY confirm dialog causing AJAX malfunction

I am encountering an issue where I am trying to execute an ajax function only after the user confirms a dialogue using JQUERY confirm. Strangely, when I include the confirmation step, my code throws an error and does not function properly. It's worth ...

Flipping json stringify safety

In my NextJS React application, I encountered an issue with circular references when using getInitialProps to fetch data. Due to the serialization method used by NextJS involving JSON.stringify, it resulted in throwing an error related to circular structur ...

Upon script load, a random item from an array will be displayed and recorded in a separate array

I'm working on a fun code project where I aim to display random animal names in different colors that change when a specific keyboard key is pressed. The challenge I'm facing is that the first random animal name in a random color only appears aft ...

Populate Vue components dynamically without the need for additional frameworks like Nuxt in Vue3

My goal is to develop a checksheet application using Vue, where the tasks are specified in an excel file. ===== To start, task A needs to be completed. Followed by task B. and so on... ===== I am considering creating a CheckItem.vue component fo ...

Sending a form cancellation submission within a nested function call

I need help preventing my form from submitting in case the confirmation message is cancelled. How can I achieve this within the each() loop? $('#myForm').submit(function() { var inputs = $(this).find('input:checked'); inputs.ea ...

Disabling buttons in a Fiori UI5 application using HTML: A step-by-step guide

I don't have much experience with scripting languages. I am attempting to hide buttons within a SAP Fiori app by using the "Inspect element" tool in the Mozilla browser. When I delete the HTML code, the button disappears, but I would like to accomplis ...

The issue arises when React child props fail to update after a change in the parent state

Here's the main issue I'm encountering: I am opening a websocket and need to read a sessionId from the first incoming message in order to use it for subsequent messages. This should only happen once. I have a child component called "processMess ...

Is it possible to represent a recursive variable using CSS?

When it comes to the html structure: <body> <div> <div> <div> ... </div> </div> </div> </body> Is there a method to create recursive variables that utilize their parent's value: body ...

Verify that the string does not have any repeating characters

I need assistance with a code that checks if all characters in a string are unique. I've noticed that the current code always returns true, which seems to be due to the false output of the if condition unless the first two characters in the sorted lis ...

The power of Karma, AngularJS, Bootstrap, and the window variable working

As I work on testing my application, I am facing an issue with loading files using Karma into PhantomJS. The problem arises when one of the files triggers a page reload due to window variables. The files are being included in this manner: files: [ &a ...

Encountering a peculiar problem with the Bootstrap Carousel where the first slide fails to load

There seems to be an issue with the bootstrap carousel where the first slide appears empty initially, but once you slide to the second slide it starts working fine. Navigating through all slides is still possible. <div id="mediakit_carousel" class="car ...

`At a loss: jQuery failing to retrieve JSON data`

I'm having trouble with a basic script that is supposed to fetch data from a JSON feed and display it in an alert. Despite having loaded jQuery correctly and checked for common issues, the code doesn't seem to be working. I am using jQuery and ca ...

Tips for displaying and concealing columns in Blazor QuickGrid based on breakpoints

I encountered an issue when attempting to hide a PropertyColumn on small screens in Blazor 8 using the regular Bootstrap 5 method. By adding Class="d-sm-none d-md-block" to the QuickGrid component's PropertyColumn, it seems that the Bootstra ...

How to modify a value in a document within a MongoDB collection

I'm having an issue with updating the 'panel' field in both the cards collection and projects collection. Here is my code snippet: const project = await Project.findOne({"code":currentUser.groupcode}); // this works const ...

Ways to retrieve the total of all the values stored within an object created using a constructor function

Currently, I am in the process of creating an RPG character builder where each character is allocated 10 points to distribute among their characteristics and select advantages. Character Constructor function character(str, dex, con, int, wis) { this ...

Displaying a MySQL blob image in an HTML file with Vue.js: A step-by-step guide

Here is a Vue file that I have: export default { data(){ return{ info: { name: '', image: '', }, errors: [] } }, created: function(){ thi ...