473,748 Members | 9,931 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

mouse cursor position

How can I get the coordinates of the mouse cursor in Mozilla browsers as
well as Opera and IE6?
I'm struggling to understand how to capture mouse movement events with
Mozilla/Netscape/Firefox and I've Googled so much my brain hurts.

http://www.ghpkendal.co.uk/TestPages/Test.htm

Move your cursor over the yellow area and you should see the mouse
coordinates echoed above.

The following javascript function works for Opera and IE6 when called by
onMouseMove="mo veDiv()". How do I adapt it to cope with the browser versions
mentioned above?
The code snippet in question is listed below. I've not included any feature
detection to keep things simple.

divX & divY are locally declared numerical variables in the test page.
'cpos' is the ID of a <div> element used to display the mouse cursor
coordinates.

function movement()
{
divX = event.x
divY = event.y
document.getEle mentById('cpos' ).innerHTML = "X=" + divX + "<br>Y=" + divY
}
Jul 23 '05 #1
10 18081
On Fri, 12 Nov 2004 09:25:31 -0000, Danny@Kendal
<da***@STOPSPAM ghpkendal.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="mo vement(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.client X) && 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.
Jul 23 '05 #2
"Michael Winter" <M.******@bluey onder.co.invali d> wrote in message
news:opshcl10u4 x13kvk@atlantis ...
On Fri, 12 Nov 2004 09:25:31 -0000, Danny@Kendal
<da***@STOPSPAM ghpkendal.co.uk > wrote:
How can I get the coordinates of the mouse cursor in Mozilla browsers as
well as Opera and IE6?


[snip]


You absolute feckin' beauty! Thank you *very* much for your time.

I've updated the test page with all the testing inlined to make it clearer
(to me) what is happening. It seems to work in all the browsers I've tried
so far without throwing up any javascript errors or alerts.

I've renamed it and I'll leave it up indefinitely for reference.
http://www.ghpkendal.co.uk/TestPages/MouseCoords.htm

I've printed out your very helpful reply for future tinkering. I didn't know
you could return values from a function in that way - particularly returning
the results from one function into another so you only have one place from
where to extract the values.

I've tried Firefox 1.0 - very nice rendering but I prefer the Opera
interface. I still like IE6 but it needs updating.
Jul 23 '05 #3
On Fri, 12 Nov 2004 12:16:41 -0000, Danny@Kendal
<da***@STOPSPAM ghpkendal.co.uk > wrote:

[snip]
You absolute feckin' beauty! Thank you *very* much for your time.
You're welcome. :)
I've updated the test page with all the testing inlined to make it
clearer (to me) what is happening. It seems to work in all the browsers
I've tried so far without throwing up any javascript errors or alerts.
It shouldn't. I still don't like the global variables.

[snip]
I've printed out your very helpful reply for future tinkering. I didn't
know you could return values from a function in that way - particularly
returning the results from one function into another so you only have
one place from where to extract the values.
If it helps, consider it this way...

When you define a function using

function identifier(/* ... */) {
/* ... */
}

it's analogous to

var identifier = function(/* ... */) {
/* ... */
};

That is, you create a variable, identifier, and assign a function to it.

Now, functions are objects and, just like with other objects, you can use
more than one identifier to refer to the same object.

Combining those two principles together, you can see that you could assign
the reference to some function, A, to the identifier of some other
function, B. Both A and B would now refer to the same function[1], so you
can call that function with either identifier. If you make that assignment
based on some condition, you can create a self-configuring system: if you
determine that one function isn't appropriate for a specific action,
replace it with another that is.

Since Richard Cornford gave a very nice display of this idea a while ago,
it's something I think about a lot.
I've tried Firefox 1.0 - very nice rendering but I prefer the Opera
interface.
Me, too. I keep Mozilla (several versions) and Firefox for testing.
I still like IE6 [...]


And just when I thought there was hope for you. :P

Good luck,
Mike
[1] If the identifier, B, was the only reference to the second function,
that function will be destroyed. That is:

function A() {} // 1
function B() {} // 2
B = A;

Function 2 can't be accessed any more as nothing refers to it, so it's
deleted on the next garbage collection cycle.

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #4
DU
Michael Winter wrote:
On Fri, 12 Nov 2004 09:25:31 -0000, Danny@Kendal
<da***@STOPSPAM ghpkendal.co.uk > wrote:
How can I get the coordinates of the mouse cursor in Mozilla browsers
as well as Opera and IE6?


The answer is that you need cross-browser code since MSIE 6 does not
support DOM 2 Events interface attributes and methods.

[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="mo vement(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.


x and y event properties are coordinates relative to relatively
positioned elements in MSIE.

Interactive demo on event.x and event.y
http://www10.brinkster.com/doctorunc...ngEventXY.html

I've reopened an Opera bugfile 123298 on this btw.
http://www10.brinkster.com/doctorunc...a7EventXY.html
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;

The above does not make sense. clientX and clientY are well supported
event properties in browsers. x and y are not and are not very useful.
Even support for x and y properties were dropped in Mozilla (they were
supported in NS 4). And as said before, x and y are relative to
relatively positioned elements while clientX and clientY are relative to
browser window viewport (not to document)
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};}

I doubt this mC function is really needed.

/* Tests if the given argument is a number. */
function isN(o) {return 'number' == typeof o;}

isN is also not needed as the function isNaN is already available and
widely implemented in javascript browsers.
/* Check if the clientX and clientY event properties are
* supported. If so, replace the default, gC, with dC.
*/
if(isN(e.client X) && 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);
});


There may be (not sure; it depends on the design requirements) another
problem which is not addressed in the above code: when the page content
exceeds browser window viewport: the returned coordinates will not
return the coordinates in the document scroll view.

Interactive window properties, methods, events page
http://www10.brinkster.com/doctorunc...dowsMSIE6.html
http://www10.brinkster.com/doctorunc...indowsNS6.html
http://www10.brinkster.com/doctorunc...owsOpera7.html

DU
--
The site said to use Internet Explorer 5 or better... so I switched to
Mozilla 1.7.3 :)
Jul 23 '05 #5
On Fri, 12 Nov 2004 16:01:08 -0500, DU <dr*******@hotN OSPAMmail.com> wrote:

[snip]
http://www10.brinkster.com/doctorunc...a7EventXY.html
From my reading of the reference, I see no bug:

"This property returns the y-coordinate of the closest relatively
positioned parent element of the element that fires the event. If
the event firing element is relatively positioned, then the
y-coordinate from the boundary of the element is returned."

As both images are relatively positioned, the offset should be with regard
to their borders.

[snip]

[MW:]
var divX = evt.x || evt.clientX,
divY = evt.y || evt.clientY;


The above does not make sense.


It makes sense, but it's unnecessary. I didn't check whether IE supported
clientX/Y, and I just assumed it didn't. My bad.

[snip]
function mC(e) {return {x: e.x, y: e.x};}


I doubt this mC function is really needed.


In light of the above, no, it isn't.
/* Tests if the given argument is a number. */
function isN(o) {return 'number' == typeof o;}


isN is also not needed as the function isNaN is already available and
widely implemented in javascript browsers.


The function, isN (isNumber), performs a different action than isNaN. The
former checks that the argument is a number, whilst the latter checks if
the argument can be type-converted to a number.

[snip]
[...] the returned coordinates will not return the coordinates in the
document scroll view.
Could you elaborate, specifically with regards to what you're refering to
with "document scroll view"?

[snip]
http://www10.brinkster.com/doctorunc...owsOpera7.html


That's a dead link, by the way. The correct URL is
<URL:http://www10.brinkster .com/doctorunclear/HTMLJavascriptC SS/DUWindowsO7.htm l>.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #6
On Fri, 12 Nov 2004 21:25:30 +0000, "Michael Winter"
<M.******@bluey onder.co.invali d> wrote in message
<opshde78iyx13k vk@atlantis>:
On Fri, 12 Nov 2004 16:01:08 -0500, DU <dr*******@hotN OSPAMmail.com>
wrote:

[snip]
http://www10.brinkster.com/doctorunc...a7EventXY.html


From my reading of the reference, I see no bug:

"This property returns the y-coordinate of the closest relatively
positioned parent element of the element that fires the event. If
the event firing element is relatively positioned, then the
y-coordinate from the boundary of the element is returned."

As both images are relatively positioned, the offset should be with
regard to their borders.

[...] the returned coordinates will not return the coordinates in the
document scroll view.


Could you elaborate, specifically with regards to what you're refering
to with "document scroll view"?


(the OP posting from home)

If the browser window is resized so that the viewport needs scrolling then
the script I'm using doesn't return the position of the cursor in the
viewport but the position relative to the document. I don't really need to
fix it but I'll have a play when I'm back at work.

It's not really an issue in my real application as the area where the
mouse cursor position is needed is fairly small. I try, wherever possible,
to design for a minimum of 640x480 pixels.

Today has been a good day - I got a troublesome javascript to work and
fixed several CSS cross-browser compatibility problems. A complete
contrast to yesterday which was spent staring into space going 'duh'.

--
FZS600 - Silver/Black
GS125 - Black/Rust
Ford 100E Prefect - Black, naturally
Whisky - Aberlour Cask Strength
Jul 23 '05 #7
Michael Winter wrote:
Danny@Kendal wrote: <snip> Since Richard Cornford gave a very nice display of this
idea a while ago, it's something I think about a lot.

<snip>

Yep was right, he know you would not be able to resist the idea ;)

In retrospect the object I tend to use to acquire mouse position
information was among the first self-reconfiguring object that I wrote
(before I recognised that as an exploitable concept in itself). It
doesn't do much function swapping but instead re-assigns strings used as
property names and object references to configure itself. It was
designed to keep the mousemove handling function as fast and simple as
possible and to exploit the fact that you don't ever need to know that
mouse position as frequently as mousemove events happen. It also
normalises the co-ordinates to the same relative system (offsets into
the HTML page). I have posted it a few times before but it probably
deserves another airing in this context:-

var MoveFollow = (function(){
var global = this;
var theInterface = {
getPageX:functi on(){
return (((readScroll.s crollLeft|0) -
(readScroll.cli entLeft|0)) + x);
},
getPageY:functi on(){
return (((readScroll.s crollTop|0) -
(readScroll.cli entTop|0)) + y);
},
getPageXY:funct ion(){
return {x:this.getPage X(),y:this.getP ageY()};
},
getTarget:funct ion(){
return lastTarget;
},
upDate:function (ev){
mm(ev);
}
};
var x = 0, y = 0;
var readScroll = {scrollTop:0,sc rollLeft:0,
clientLeft:0,cl ientTop:0};
var lastTarget = null;
var posReadX = 'pageX';
var posReadY = 'pageY';
function mm(e){
e = e||global.event ;
x = e[posReadX];
y = e[posReadY];
lastTarget = e.target||e.src Element;
}
function initEvent(ev){
if(document.bod y){ //Not safe to configure until the
//BODY exists in the DOM.
ev = ev||global.even t;
if(ev){
if(typeof ev.pageX != 'number'){ //Opera 7 has pageX
posReadX = 'clientX';
posReadY = 'clientY';
if((typeof document.compat Mode == 'string')&&
(document.compa tMode.indexOf(' CSS') != -1)&&
(document.docum entElement)){
readScroll = document.docume ntElement;
}else if((document.bo dy)&&(!global.o pera)){
//Not an Opera <= 6 browser (becaue its
//clientX/Y are page-relative already).
readScroll = document.body;
}
}
setUpOnMouse(mm );
mm(ev);
}
}
}
function setUpOnMouse(f) {
if(document.onm ousemove != f){
document.onmous emove = f;
if((document.ca ptureEvents)&&( global.Event)&&
(document.layer s)&&(typeof Layer == 'function')){
//Netscape 4 *only* (or probably harmless in context)
document.captur eEvents(Event.M OUSEMOVE);
/* captureEvents on Netscape 6+/Mozila/Gecko would
cause all move events to be processed in the
capturing phase in addition to when they arrived
at the target. There is no reason to be
processing the same event twice (and good reasons
for avoiding doing so).
*/
}
}
}
setUpOnMouse(in itEvent); // Attach initEvent as the initial
// mousemove handler.
return (function(){
return theInterface;
});
})();

Richard.
Jul 23 '05 #8
On Sat, 13 Nov 2004 00:36:50 -0000, Richard Cornford
<Ri*****@litote s.demon.co.uk> wrote:

[snip]
Yep was right, he know you would not be able to resist the idea ;)
It's always fun to have a new toy to play with. :)
I have posted it a few times before but it probably deserves another
airing in this context:-


I can't say that I've seen it before. I'm glad you posted it, though. My
knowledge is weak when it comes to the various dimension-related
properties.

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #9
On Fri, 12 Nov 2004 21:25:30 GMT, Michael Winter
<M.******@bluey onder.co.invali d> wrote:
On Fri, 12 Nov 2004 16:01:08 -0500, DU <dr*******@hotN OSPAMmail.com>
wrote:


[snip]
[...] the returned coordinates will not return the coordinates in the
document scroll view.


Could you elaborate, specifically with regards to what you're refering
to with "document scroll view"?


I think I know what you mean, now.

If the cursor is twenty pixels in from the left-hand edge, you'd expect
clientX to return 20. However, if the document was scrolled ten pixels to
the right, you might expect clientX to return 30 but it should still
return 20.

Based on that interpretation, no my suggestion wouldn't treat a scrolled
page specially. However, from reading through Richard's, it seems his
would.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2834
by: Sameh Ahmed | last post by:
Hello there how do I send a mouse click to a specific set of coordinates in the desktop? what do I need to search for? any info is greatly appreciated. Regards Sameh
6
6997
by: jcrouse | last post by:
I have the following mouse events assigned to a label control. Is the a way I can tell which mouse button the users has clicked with? Private Sub lblP1JoyUp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lblP1JoyUp.Click If bMouseMove = False Then If bCtrlKey = True Then
3
2076
by: jcrouse | last post by:
I have created a form designer type application (with a lot of you peoples helpJ). It has label controls that are draggable at runtime. The user is also allowed to change some properties such as forecolor, backcolor and font. The labels also are rotatable and the text can also be flipped 180 degrees (the flipped text part is still being worked on). I have one context menu for all 30 labels that allows for the property changes to the labels....
4
8843
by: Henry Wu | last post by:
Hi, I see examples of Magnifying an area under mouse coordinates to a form or picturebox using VB6 and VC6, does anyone know how to do it under VB.NET? Its nice to use the new GDI+ for it. Thanks, Henry
13
3153
by: Lars Netzel | last post by:
Hi! I have a round area which I want to be able to move the mouse over and fire off events... how do I do that? I have drawn a FillPie Graphics and I feel that there has to be a way of getting to know if the mouse is over that area since I have the coordinates to paint the Pie but I don't know where to start or what to look for really. Best Regard
2
7279
by: Fei | last post by:
Hi, Is this possible that when the user move out a form, the mouse is disabled/hidden? I want to restrict user to use mouse just in my application. Thanks ! Fei
2
5009
by: Sam | last post by:
Hi, I can't figure out how to detect when my mouse cursor leaves a panel control. It should not trigger the event (or do anything) when the mouse leave the panel but still is over a control that is contained by the panel. I've done this : Protected Overrides Sub OnMouseLeave(ByVal e As System.EventArgs) If Cursor.Position.X > Me.Location.X + Me.Width Or Cursor.Position.Y > Me.Location.Y + Me.Height _
1
4599
by: Andy Baxter | last post by:
hello, I'm writing a panoramic image viewer in javascript. When the mouse is over the image, I want it to be a crosshair (over most of the image), or a hand/pointer (when it's over an image map region). The image map is created in javascript, but doesn't set any 'cursor' style rules. The problem I'm having is I have two images embedded inside two divs. The outer div has style='... cursor:crosshair', but when I move over the image...
3
3767
by: Morten Snedker | last post by:
If I have a number of random applications open, move the mouse cursor to a given position and do a click, the application gets the focus. That is what this simple code should illustrate: Dim pt As Point Dim wnd As IntPtr Const WM_LBUTTONUP = &H202 '//LButton up Const WM_LBUTTONDOWN = &H201 '//LButton down
4
6975
by: mike | last post by:
I have the opportunity to rescue a project that uses a mouse to sense the relative position of a machine. The hardware is built...just needs to be programmed. Stop snickering!!! I didn't do it...I just gotta fix it. I need to make some calculations on the measurements and VB6 is my language. Yes, the system mouse will corrupt the measurement, but it's an auditing function and that's acceptable.
0
8831
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9374
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9325
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9249
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4876
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3315
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.