krelay logo
Type: Series
Title: XHTML/CSS 10
Class: Coding
Date: 05.04.2007

Finding Mouse Coordinates easily.

Here is a useful little JavaScript which can help enormously in designing a web page layout. All it does is to follow your mouse and display the coordinates in the status bar. That may not seem particularly useful, but when you are trying to figure out where a div should be placed, it can save a lot of trial and error attempts. Believe me, you will come to love this script.

First, I should admit that this script isn't mine, I stole it from somewhere - can't remember where! If the person who wrote this script will contact me, I will be pleased to give credit where it is due.

Second, it is obviously quite old and as I haven't used Netscape for years, I don't know what would happen. Whatever, it works in Internet Explorer, Firefox, Konquerer and Opera. Perhaps it should be rewritten to look for "Gecko".

When I say it works, it has some surprises in some browsers. When using container divs as I have outlined in the XHTML/CSS series, you occassionally see the x coordinate change to zero as the mouse enters the centralized "main" div in IE6. That is a bug but I find it useful.
Another slight problem in Windows98 is that the tip of the cursor "arrow" doesn't quite align with the hotspot - it's one or two pixels wrong but you'll get used to that.

The script is placed in the head section of your page - just don't forget to remove it after your page is complete. It is placed on this page so that you can see how it works. You can copy it from the source, or for the lazy, here is the code:

<script language="javascript" type="text/javascript">
function writeCoor(e) {
        var x=(navigator.appName.indexOf("Netscape")!=-1)?e.pageX:event.x;
        var y=(navigator.appName.indexOf("Netscape")!=-1)?e.pageY:event.y;
        window.status="Mouse x-coordinate: "+x+" Mouse y-coordinate: "+y;
}
        if (navigator.appName.indexOf("Netscape")!=-1)
                document.captureEvents(Event.MOUSEMOVE);
                document.onmousemove=writeCoor;
</script>



The test of any script is do you use it yourself? Well, I used to use this! Actually, now I use a much more advanced script that shows a moving cross-hair. That script needs browser detection, has automatic screen resolution detection, and dynamically paints a 1x1 gif image to form the cross-hair. This is all fine unless you have other JavaScripts on the same page which then get completely screwed up.
So I am publishing the simplist script only because this series is for beginners.

My view of JavaScript is that it can be very impressive and tremendously useful but we would all be better off without it. Just count the number of websites that give "javascript error" notices in your browser and you will understand why. This script is to help you design the page - not to be part of the page.

Home

© krelay.com 2007