Why is it that every time I attempt to save a variable, it never seems to work properly

var cl = 0;
var menu = function(){

    if(cl === 0){
        $('.menu_nav').animate({left: '0px'}, 200);

        $('body').animate({left: '285px'}, 200);

        var cl = cl + 1;
        console.log("First " + cl);
    }else{
        $('.menu_nav').animate({left: '-285px'}, 200);

        $('body').animate({left: '0px'}, 200);

        var cl = cl - 1;
        console.log("Second " + cl);
    };
};

$(document).ready(function(){
    $('.menu-btn').on('click', function(){
        $(menu);
    });
});

I am attempting to create a toggle button that opens a side panel upon clicking, and then closes it when clicked again. I have experimented with += and =+ without success. Each click prints out "first 1," failing to transition to the 'else' statement as expected.

//The issue has been resolved by moving the declaration of the variable outside the function, preventing it from being reset to 0 every time the function is called. It now correctly stores and updates the variable value.

Answer №1

Whenever the function menu runs, the cl variable is reset to 0. Consider using a global variable by declaring var cl = 0; before defining your function with var menu = function(){. Within the function, replace all instances of var cl with just cl. Take a look at this example for further clarification.

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

Pseudo elements disappear when utilizing Flexbox

I am looking to create two divs that each take up 100% width, but I am open to other configurations. Additionally, the active tab should have an arrow displaying below it. Despite using flex-grow in my flexbox setup, the placement of the after pseudo-elem ...

Steps to store radio button selections in local storage

I have a quiz that includes radio buttons, and I need to save the answers on my local storage. However, I am currently stuck and unsure of what else to do. I am learning, so please don't be too hard on me. Thank you! Here is the code I have written s ...

Stopping a jQuery function from executing multiple times while it is already active - is it possible?

Currently, I am utilizing the http://jsfiddle.net/CqAU2/ plugin for image rotation on my website. The issue I am facing is that when the user clicks on the image box multiple times, it continues rotating each time. I want the click action to only be regi ...

Error message: Angular JS encountered an issue when trying to initiate the test module. The cause

When I run JavaScript within an HTML file and use AngularJS with ng-repeat function, I encounter this console error: angular.js:38 Uncaught Error: [$injector:modulerr] Clicking on the link in the error message leads to: Failed to instantiate module test ...

Retrieving JSON data using Backbone.js fetch() and translating it into a model results in get()

My current issue involves fetching a JSON file and storing it in a model for later access. However, I am encountering difficulties when trying to access the attributes through the get() method as it keeps returning undefined. The JSON file contains an arra ...

Incorporate the NestJS module seamlessly into one module from another module without the need to import it

As a newcomer to nestJs, I am currently in the process of creating a module named example.module. Within this module, I am importing another module called DB.Module. However, I have encountered an error when I do not import DB.Module in App.Module. My conc ...

Extracting information from a dynamically generated dropdown menu

I am facing a challenge with my dynamically created menu. It is important to retrieve the selected value from the menu in order to use it for a query statement. I want to clarify that this menu is not part of a form, but just a standalone element on the we ...

Automated web browser capture downloading feature

Currently, I am in the process of developing a tool to streamline tasks at my workplace. One feature we need is an aspx webpage where users can input information, then click on a submit button. When the submit button is clicked, a javascript download dialo ...

Implementing dynamic AJAX functionality for dynamically generated elements using vanilla JavaScript

Currently, I am working on developing a movie information application using ajax. However, I have encountered a challenging issue that I am struggling to resolve. After creating an ajax request, I proceed to dynamically generate content and incorporate it ...

Instant feedback from dynamically generated text boxes

As a Python developer, I am venturing into the realm of HTML. Currently, I am working on an internal tool that enables users to create directories for various projects. To achieve this, I have implemented a method for dynamically adding and removing text b ...

Hover over the horizontal dropdown menu

I have attempted to create a horizontal drop down menu using this tutorial and demo I envision the menu to look like this: I want the sub-menu to appear to the right of the parent menu, as shown in this example The next step involves the sub-menus. The ...

The initial call to the method results in an undefined return value

In my code, there is a function that retrieves distinct values from a database. Here's how it looks: function getUniqueCategories(res, req) { query = `SELECT DISTINCT name FROM product_category;`; connection.query(query, function (err, rows) { ...

Discover the chosen image displayed within an ng-repeat showcased in a separate container

I am facing an issue with a table that uses ng-repeat to display data. One of the columns contains photos. When I edit a specific entry in the table, I want the corresponding photo to be shown. How can I achieve this? The code for my table looks like this ...

Tips for transferring a dynamic set of objects to a controller within an MVC framework utilizing jQuery and Ajax

I have a form where fields are populated dynamically with objects, allowing for editing a new field before submitting the form to a different list of objects. Currently, I am employing an Ajax form for this purpose, but I am facing an issue where the < ...

Switching the input of data from a string format to a date format

One of the components in my registration form requires the user to input their start date. I am currently utilizing a MEAN Framework, specifically AngularJs for the front end development. Progress so far: Initially, I attempted using the code snippet bel ...

Failed commitments in JavaScript without a catch block (unhandled rejection)

When working on my project in VueJs JavaScript, I want to be able to see console messages if any of my Promises are not fulfilled and do not have a catch block. I attempted using the following code: Promise.reject("error!"); window.addEventListener(&apos ...

What is the best way to incorporate the "child_process" node module into an Angular application?

Trying to execute a shell script in my Angular application has been quite the challenge. I came across the "child process" node library that might be able to help me with this task. However, every attempt to import the library led me to the error message: ...

Javascript tabs with clickable links

I have created a page with a series of thumbnails that reveal content below when clicked. The content is positioned absolutely and set to display:none, with javascript changing this for each thumbnail. (I am not very familiar with javascript and learned t ...

Exploring the distinctions among different material design frameworks

Confirming my grasp of the situation here. Material design is an interface building approach developed by Google. Material lite is Google's public implementation of this concept. serves as an independent open-source adaptation. In addition, Angul ...

Comparison between AJAX and HTML headers for submitting data using JQuery and Rails

This situation is a bit unique... I have a collection of checkbox images that trigger form submission when clicked, utilizing the following Javascript: $('#pin_rose').simpleImageCheck({ image: '/images/rose.png', imageChecked: &ap ...