Toggle a variable value in JavaScript

Posted on 2006-05-10
Last Modified: 2012-05-05

In my application, I have a OnMouseDown event. Each time the mouse is down, which trigges the event and cause a variable (global)  toggled. However, it is not working. Could someone take a look of the code below? I appreciate the help.

//a global variable
var down = -1;

function toggle(){

        if (down == -1)
            down = 1;
        if (down == 1)
            down = -1;


this fucntion toggle is called via OnMouseDown event. It seems the value is always set to -1 when mouse is down


Question by:penglu

    Author Comment


    Never minde. I made a mistake
    LVL 8

    Accepted Solution

    You cant test it like that...

    How about just mult your value by -1?

    1 * -1 = -1
    -1 * -1 = 1
    LVL 12

    Expert Comment

    I usually use the true/false,   down = !down;

    does the same job as radnor's.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    Uploading files to the web server has become common part of almost any kind of web application. People use different technologies to solve this, but regardless of the technology used, it is always useful to have some kind of progress indicator shown…
    Problem to be resolved in this article Currently, development of website and web application can be done without writing thousands of lines of programming code by hand. Description This can be done through by using a open source framework such …
    The viewer will learn how to dynamically set the form action using jQuery.
    This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

    733 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now