Search code examples
javascriptjquerywhile-looponmousemove

How to store a value generated in a while loop to a variable for later use in JQuery


I have the code below which is executed by the "mousemove" event:

$("div").on("mousemove", function( event ) {
    var k = 0;
    var x = 0;
    while(k<y){
        k++;
        x = k;
    }
}

The problem is that once the loop has already run and stopped, and the mouse moves one pixel from current position, and it happens that the condition has not been met, I loose the value of k++ which is var x = k; Instead, var x is reset to 0 (zero), as it was before the loop. I need to keep the value of var x = k++ for later use even after the cursor moves.

Please advice. Thanks.


Solution

  • Just make sure you assign variable x a value outside the loop so that you can retain the new value of x when the loop exits.

    Note: Make sure the var x inside the loop is a global x by deleting the "var" before x as shown below. This way the value of x will be accessible for use outside the loop and any functions wrapping the loop.

    var x = 0;
    
    $("div").on("mousemove", function( event ) {
    var k = 0;
      while (k<y){
        k++;
        x = k; //Note that it's "x=k" and not "var x = k". This makes x global
        }
      }