On Fri, 12 Nov 2004 09:25:31 -0000, Danny@Kendal
<da***@STOPSPAMghpkendal.co.uk> wrote:
How can I get the coordinates of the mouse cursor in Mozilla browsers as
well as Opera and IE6?
[snip]
divX & divY are locally declared numerical variables in the test page.
No, they aren't. They're globally declared.
[snip]
function movement()
{
divX = event.x
divY = event.y
The first problem is that you're accessing the event object as though it's
global. Whilst this might be true in IE, and browsers that emulate it for
compatibility (like Opera), Netscape-emulating/DOM-conforming browsers
must use a local event object. If the event listener is added directly,
this object is passed as an argument. In intrinsic events added through
HTML, there is an implicit local variable called "event". Quite
conveniently really, as this allows for:
... onmousemove="movement(event);" ...
which will work with both IE and conforming browsers.
That could change your code to:
function movement(evt) {
var divX = evt.x,
divY = evt.y;
/* [write output] */
}
However, there's still one more problem: x and y aren't standard
properties of the event object. The W3C defines clientX/Y for coordinates
within the browser viewport. You could get away with:
var divX = evt.x || evt.clientX,
divY = evt.y || evt.clientY;
but something more complex may be more reliable.
var movement = (function(e) {
/* The default getCoordinates (gC) function. If neither the
* Microsoft or DOM approach is deemed supported, this will be
* used to always return (0, 0).
*/
function gC(e) {return {x: 0, y: 0};}
/* The DOM getCoordinates (dC) function. */
function dC(e) {return {x: e.clientX, y: e.clientY};}
/* The Microsoft getCoordinates (mC) function. */
function mC(e) {return {x: e.x, y: e.x};}
/* Tests if the given argument is a number. */
function isN(o) {return 'number' == typeof o;}
/* Check if the clientX and clientY event properties are
* supported. If so, replace the default, gC, with dC.
*/
if(isN(e.clientX) && isN(e.clientY)) {gC = dC;}
/* If not, try again with the x and y properties and replace
* gC with mC if successful.
*/
else if(isN(e.x) && isN(e.x)) {gC = mC;}
/* Now our testing is out of the way, replace the initial
* function with a streamlined version and call it.
*/
(movement = function(e) {
var div = gC(e);
/* [write output using div.x and div.y] */
})(e);
});
Please be aware that if you change the name, movement, you must edit the
line
(movement = function(e) {
accordingly.
[snip]
Tested on IE 6, Firefox 0.9.3 (must get round to install 1.0) and Opera
7.54.
Hope that helps,
Mike
--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.