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

advertisements

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.


The best place to store such a value is in a data attribute of the element. Let's say you have several div elements on your page, your current set up requires you to have a unique variable for each div:

$('div').on('mousemove', function( e ) {
    var k = $(this).data('k') || 0;
    //......
    $(this).data('k', +k+1);
    console.log( $(this).data('k') );
});

$('div').on('mousemove', function( e ) {
        var k = $(this).data('k') || 0;
        //......
        $(this).data('k', +k+1);
        console.log( $(this).data('k'), this );
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="div1">DIV 1</div>
<div class="div2">DIV 2</div>
<div class="div3">DIV 3</div>