Using Javascript & jQuery, I'm trying to get the mouse coordinates of a click event to use in other Javascript functions. My problem is that global variables set within an event function do not seem to update outside the function, like global vars within other functions. For example, if I have the following global variable declaration and event function to track mouse coordinates in a div with ID "clickable_area":
var mouseXPos = 0;
var mouseYPos = 0;
$(document).ready(function(){
$("#clickable_area").click(function(e){
mouseXPos = e.pageX;
mouseYPos = e.pageY;
});
});
...unless I put all code that deals with mouseXPos and mouseYPos into the event function itself, these 2 variables are not updated and available outside the event function until after the next event. For example:
function displayCoordinates() {
console.log("mouseXPos = " + mouseXPos + " and mouseYPos = " + mouseYPos);
}
...yields:
>>mouseXPos = 0 and mouseYPos = 0
Any suggestions on how to get these 2 global vars to update outside the function once it has been triggered, or am I just running up against an inherent design demand of Javascript? Could I use a callback queue to facilitate this? I could track the "mousemove" event instead and it works fine, but I don't want the overhead of constantly tracking mouse movement.