JavaScript: Toggle between 2 functions using a single click event listener

I am facing an issue with coding a Sidebar that features an animated Burger Menu Button named "navicon1". The Menu Button utilizes the "open" class to create a cool animation effect. Moreover, I aim to have the functions "openNav" and "closeNav" toggled when clicking on the menu button.

Here is what I am looking for:

  • Upon the first click on the Menu Button (navicon1), it should change to an X shape (which currently works) and trigger the javascript function "openNav"
  • Subsequently, upon clicking the Menu Button again (navicon1), it should revert to its original form (which also works) and execute the javascript function "closeNav"

Below is my code snippet:

$(document).ready(function() {

    $('#navicon1,#navicon2,#navicon3,#navicon4').click(function() {
        $(this).toggleClass('open');
    });

});

function openNav() {

    document.getElementById("mySidenav").style.width = "75%";
    document.getElementById("main").style.marginLeft = "75%";
    document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}

function closeNav() {

    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("main").style.marginLeft = "0";
    document.body.style.backgroundColor = "white";
    check = 0;
}

The other navicons mentioned are solely for styling purposes...

Appreciate your assistance :)

Answer №1

Implementing state management with a variable:

let isNavOpen = false;
$("#navicon1").click(function() {
    if (isNavOpen) {
        closeNavigation();
        isNavOpen = false;
    } else {
        openNavigation();
        isNavOpen = true;
    }
});

Answer №2

My recommendation is to develop a single function that manages the toggleClass() method and invoke your other functions from within it depending on the current state.

$('#navicon1').click(function() {
    $(this).toggleClass('open');

    //if hasClass() then call function to open it

    //else call function to close it

});

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

Adding content to a paragraph using Jquery

I have 4 sets of data associated with a click-bind event. My goal is to retrieve the value from a hidden field in each set and display it in a paragraph elsewhere on the page when the corresponding checkbox is clicked. Currently, I'm focused on gettin ...

Nested solution object populated with promises

Looking for a solution similar to the npm libraries p-props and p-all, but with the added functionality of recursively resolving promises. const values = { a: () => Promise.resolve(1), b: [() => Promise.resolve(2)], c: { d: () =&g ...

Run the setInterval function immediately on the first iteration without any delay

Is there a way to display the value immediately the first time? I want to retrieve the value without delay on the first load and then refresh it in the background. <script> function ajax() { ...

Guide to setting up parameterized routes in GatsbyJS

I am looking to implement a route in my Gatsby-generated website that uses a slug as a parameter. Specifically, I have a collection of projects located at the route /projects/<slug>. Typically, when using React Router, I would define a route like t ...

Retrieve the current height of the iFrame and then set that height to the parent div

Within a div, I have an iFrame that needs to have an absolute position for some reason. The issue is that when the iFrame's position is set to absolute, its content overlaps with the content below it. Is there a way to automatically adjust the height ...

Uh-oh! Trouble loading web app dependencies: 404 Error

Currently, I have a functional SailsJS boilerplate application. The next step I am trying to undertake involves integrating Angular-Material as a dependency in order to kickstart some UI development tasks. However... After installing angular-material usin ...

How can I change the displayed value of a 'select' element programmatically in Internet Explorer?

My interactive graphic has a drop-down menu implemented with a <select> element. Everything functions correctly, except when using Internet Explorer. The issue arises when attempting to programmatically change the selected value of the <select> ...

Switch back and forth between two tabs positioned vertically on a webpage without affecting any other elements of the page

I've been tasked with creating two toggle tabs/buttons in a single column on a website where visitors can switch between them without affecting the page's other elements. The goal is to emulate the style of the Personal and Business tabs found on ...

Issue with callback function not triggering after comment deletion in REACT

Although I am successfully able to delete the comment, I am facing an issue where the callback function is not being invoked. My suspicion is that it might be related to how I pass multiple arguments to the function, but I cannot confirm this. Below is th ...

Exploring the ins and outs of console interactions in JavaScript

I have come across a problem on Hacker Rank that seems quite simple. The task involves working with N strings, each of which has a length no more than 20 characters. Additionally, there are Q queries where you are provided a string and asked to determine ...

My code fails to recognize the top property when the window size is 1300px

Error at the Top Not Being Recognized: Hello, I am facing an issue where the top part of the webpage does not behave correctly when the window size is less than 1300px. The condition set for 100% top only applies after refreshing the page; otherwise, it d ...

Unable to update values in Google Sheets using the node.js API

I have been working on a node.js project that involves extracting the location of a cell based on a person's name and date. While I am able to determine this information easily, I encounter difficulties when trying to update the cell using the .update ...

Is it possible to select multiple drop-down lists on a webpage using Python and Selenium?

I am encountering an issue while attempting to click on multiple dropdown lists within a page. I continuously receive an error message stating that my list object does not have an attribute 'tag_name'. Here is my code snippet: def click_follow_ ...

Tips for setting up Nginx with Node.js on a Windows operating system

I am looking to set up Nginx on my Windows machine in order to run two node applications. Can anyone provide guidance on how to accomplish this? I have attempted to download Nginx 1.6.3, but have had trouble finding instructions specifically for running i ...

How to fetch a single document from a nested array using Mongoose

Currently, I am working on a MongoDB database using Mongoose in Node.js. The collection structure resembles the following: { cinema: 'xxx', account: 'yyy', media: { data: [{ id: 1, name: 'zzz& ...

The video continues playing even after closing the modal box

I am facing an issue with my code where a video continues to play in the background even after I close the modal. Here is the code snippet: <div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria- ...

Upgrading an Express 2.x application to Express 3.0

I am currently studying NodeJs and Express and am in the process of converting a tutorial app from Express 2.5.9 to version 3.0. The following code is now causing an error "500 Error: Failed to lookup view "views/login". How can I update this to render cor ...

When an input is disabled in "react-hook-form", it may return undefined

Within my React application, there exists a form containing various input fields. I have enclosed these fields using FormProvider imported from react-hook-form and utilized register within each field. import { useForm, FormProvider, useFormContext } from & ...

Guide to triggering React Material-UI modal and filling it with data from an Ajax request when a button is clicked

Despite my efforts to find a similar question, I couldn't come across one. My apologies if I overlooked it. Currently, I am working on a React Material-UI project to develop a basic web application. Within this application, there is an XGrid that disp ...

Dynamic Divider for Side-by-Side Menu - with a unique spin

I recently came across a question about creating responsive separators for horizontal lists on Stack Overflow While attempting to implement this, I encountered some challenges. document.onkeydown = function(event) { var actionBox = document.getElementB ...