getMousePosition

This is another one from the frequently asked questions basket. The getMousePosition script supplied here takes an event as it's parameter and returns an object with the attributes x & y set to the position of the mouse. You've probably already noticed it updating the input below.

Mouse Position :

The code

Here's the code that's doing the work. The getMousePosition function returns the mouse position of the supplied event object. The showMousePos function grabs the mouse position and then updates the input so we can see it. The init function just adds a handler for the mousemove event.

function getMousePosition(e) { return e.pageX ? {'x':e.pageX, 'y':e.pageY} : {'x':e.clientX + document.documentElement.scrollLeft + document.body.scrollLeft, 'y':e.clientY + document.documentElement.scrollTop + document.body.scrollTop}; }; function showMousePos(e) { if (!e) e = event; // make sure we have a reference to the event var input = document.getElementById('mousepos'); var mp = getMousePosition(e); input.value = 'x : ' + mp.x + ', y : ' + mp.y; }; function init() { document.onmousemove = showMousePos; }; window.onload = init;

Comments

If you've got any questions or feedback about this article please post them in the Dynamic Tools Javascript Forum.