5

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.

user2613971
  • 895
  • 6
  • 14
John Williams
  • 51
  • 1
  • 2
  • Your code as written looks like it should work. Are you perhaps logging the mouse positions before you click? Where are you calling displayCoordinates? – arghbleargh Aug 14 '13 at 21:38
  • [Shenanigans](http://jsfiddle.net/8YME9/) – Jason P Aug 14 '13 at 21:38
  • All of this is just hypothetical. I'm in the design phase of a project, and I foresee several instances where it would be ideal to have different functions share the click event data without having to be inside the event function itself. Global vars updated within a function can be shared outside the function, however this doesn't seem to work within an event function such as this. – John Williams Aug 14 '13 at 21:49

1 Answers1

0

If you insist on using Global Variables (bad idea in my opinion) try this. Asign them as window.mouseXPos = 0, then recall them simply as mouseXPos. However, assigning them outside the scope of function load should make them global, using window. will ensure such.

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>
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81