seus seus - 6 months ago 10
jQuery Question

jquery - Update a variable outside a animate function, dynamically

How would I go about updating a variable outside a function dynamically, then being able to use it another function for example. In this situation the user presses the right key and moves 50px.

var barryPosX;

function getCurrentPos() {
position = $("#barry").position();
barryPosX = position.left;
return barryPosX
};


$(document).keydown(function(e) {
switch(e.which) {
case 39:
$("#barry").stop().animate({
left: '+=50'
}, function() {
barryPosX = getCurrentPos();
})
break
case 37:
$("#barry").stop().animate({
left: '-=50'
});
break
}
})


I'd like to update the global variable 'barryPosX' to the current position of '#barry'. I am aware that this can be done under the jquery animate function, but since I want to be able to use the barryPosX variable outside the animate function like so...

function changeScreen() {
if(barryPosX => canvas.width())
{console.log("true")}
}

Answer

barryPosX is already in the global scope, so you can just assign the value to barryPosX directly in the getCurrentPos function just like you've done. You don't need to assign the value to barryPosX from within the animation callback.

If you wanted, you could also pass the value into the getCurrentPos function like so:

var barryPosX;

function getCurrentPos(position) {
  barryPosX = position.left;
};

$(document).keydown(function(e) {
  switch(e.which) {
    case 39:
      $("#barry").stop().animate({
        left: '+=50'
      }, function() {
          position = $("#barry").position();
          getCurrentPos(position);
      })
    break
    case 37:
      $("#barry").stop().animate({
        left: '-=50'
      });
    break
  }
})

The value of barryPosX will also be accessible within the changeScreen function.