How to update global var Javascript inside click event function

Using Javascript and jQuery, I am trying to get the mouse coordinates for the click event for use in other Javascript functions. My problem is that the global variables set inside the function of the event do not seem to be updated outside the function, for example, global vars in other functions. For example, if I have the following global variable declaration and an event function for tracking mouse coordinates in a div with the 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 the code that deals with mouseXPos and mouseYPos in the event function, these 2 variables are not updated and are not available outside the event function until the next event. For instance:

 function displayCoordinates() { console.log("mouseXPos = " + mouseXPos + " and mouseYPos = " + mouseYPos); } 

... gives:

 >>mouseXPos = 0 and mouseYPos = 0 

Any suggestions on how to get these 2 global vars to update outside the function after it starts, or am I just coming across the inherent Javascript design? Can I use a callback queue to facilitate this? I could track the "mousemove" event, and it works great, but I don't want the overhead of constantly tracking mouse movement.

+4
source share
1 answer

If you insist on using Global Variables (a bad idea in my opinion) try this. Assign them as window.mouseXPos = 0 , then name them simply as mouseXPos . However, assigning them outside the function loading area should make them global, using window. will provide this.

See my example:

jsFiddle

Js

 <script type="text/javascript"> window.mouseXPos = 0; window.mouseYPos = 0; $(function() { // <-- Same as `$(document).ready(function(){` $(document).on('click', '#clickable_area', function(e) { mouseXPos = e.pageX; mouseYPos = e.pageY; }); }) </script> 
0
source

Source: https://habr.com/ru/post/1497122/


All Articles