Jquery / javascript - accessing variables from outside a function

I am trying to use a variable value outside the function in which it was defined. Thought I. I just needed to declare a variable outside the function, but that did not shorten it. Should be easy for those who know?

Fiddle here

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 everyone, especially Andy E with the explanation and.

+6
javascript variables jquery
source share
4 answers

You assign variables through the callback function, which is registered in the event handler. This means that when this is done:

 $('#var2').html(readOut2); 

readOut2 is undefined because it has not yet been set by the mousemove handler function. This handler will not fire until the current code in the queue stops executing and the user moves his mouse. You can define a function in the same scope as variables and call this function from the mousemove handler.

Re: your comments on another answer, you can use a timer:

 jQuery(document).ready(function() { var readOut1; var readOut2; $(document).mousemove(function(e) { readOut1 = e.pageX; readOut2 = e.pageY; $('#var1').html(readOut1); }); window.setInterval(function () { $('#var2').html(readOut2); }, 300); })​; 
+5
source share

I think you want to track the coordinates of the cursor, check the updated source code:

 jQuery(document).ready(function() { var readOut1; var readOut2; $(document).mousemove(function(e) { readOut1 = e.pageX; readOut2 = e.pageY; $('#var1').html(readOut1); $('#var2').html(readOut2); }); })​ 

http://jsfiddle.net/xSa2T/2/

+2
source share

Sounds like a sync issue.

This line

 $('#var2').html(readOut2); 

will be called in document.ready, while the mousemove event has not yet been triggered, so readOut2 does not matter yet.

+1
source share

but you want to use the value outside the mousemove function

Since the readOut1 and readOut2 cannot be set before the mousemove event handler is run, you will have to call any code that will use these variables from the mousemove handler.

Example:

 $(document).mousemove(function(e) { readOut1 = e.pageX; readOut2 = e.pageY; doStuffWithReadOuts(/* possibly passing readouts as arguments instead... */); }); function doStuffWithReadOuts() { $('#var1').html(readOut1); $('#var2').html(readOut2); } 
+1
source share

All Articles