views:

388

answers:

2

I've found this snippet on Ajaxian, but I can't seem to use the cursor.y (or cursor.x) as a variable and when the function is called as such it does not seem to work. Is there a syntax problem or something else?

function getPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
      cursor.x = e.pageX;
      cursor.y = e.pageY;
    } 
    else {
      cursor.x = e.clientX + 
        (document.documentElement.scrollLeft || 
         document.body.scrollLeft) - 
         document.documentElement.clientLeft;
      cursor.y = e.clientY + 
        (document.documentElement.scrollTop ||
         document.body.scrollTop) - 
         document.documentElement.clientTop;
    }
    return cursor;
}

I'd preffer not to use jQuery UI if possible, since I've always thaught of jQuery and librarys as a bit of an overkill for most JS programing.

A: 

This snippet must be called inside a mouse event handler, with the event object from the handler.

SLaks
Yes I called it like this onclick="getPosition(e); anotherfunct();"(and yes, the variable is used within anotherfunct()
Constructor
You need to pass `event`, not `e`. Also, how are you passing the return value to `anotherfunc`?
SLaks
example: mouseposx=cursor.x
Constructor
This function does not create a global `cursor` variable. You need to explicitly pass its return value to `anotherFunc` as a parameter, or modify the function.
SLaks
even if I remove the var infrom of cursor (making it a global variable) it still doesn't work, why?
Constructor
Are you passing `event` instead of `e`? It works for me: http://jsbin.com/onewe/2/edit
SLaks
thank you, it works great! Nice tool for javascript examples btw
Constructor
Then you should accept this answer by clicking the hollow check.
SLaks
A: 

This has always been difficult to achieve cross-browser, but this is about as good as you can get...

<!DOCTYPE html>
<html>
  <head>
    <title>Javascript Test</title>
    <script type="text/javascript"> 
      window.onload = function() {
        document.onmousemove = function(e) {
          if(!e) e = window.event;

          if(e.pageX == null && e.clientX != null) {
            var doc = document.documentElement, body = document.body;

            e.pageX = e.clientX
                    + (doc && doc.scrollLeft || body && body.scrollLeft || 0)
                    - (doc.clientLeft || 0);

            e.pageY = e.clientY
                    + (doc && doc.scrollTop || body && body.scrollTop || 0)
                    - (doc.clientTop || 0);
          }

          document.getElementById("pos").innerHTML = e.pageX + ", " + e.pageY;
        }
      } 
    </script>
  </head>
  <body> 
    <h1>Position: <span id="pos">0, 0</span></h1>
  </body>
</html>
Josh Stodola
For what it's worth, this is how jQuery does it
Josh Stodola