I’m trying to use a variable value outside of the function it was defined in. Thought I. just needed to declare the variable outside the function but that doesn’t cut it. Gotta be an easy one for those who know?
jQuery(document).ready(function() {
var readOut;
var readOut2;
$(document).mousemove(function(e) {
readOut1 = e.pageX;
readOut2 = e.pageY;
$('#var1').html(readOut1);
});
$('#var2').html(readOut2);
})
Thanks to all, especially Andy E with the explaination and solution.
You’re assigning to the variables via a callback function which is registered to an event handler. This means that when this runs:
readOut2has a value of undefined because it hasn’t been set by the mousemove handler function yet. That handler won’t fire until the current queued code stops executing and the user moves their mouse. You could define a function in the same scope as the variables, and call that function from the mousemove handler.Re: your comments on another answer, you could use a timer: