Tutorial on how to get the mouse coordinates with prototype.

Download mouse coordinates sample code

I have seen a lot of questions about how to get the mouse coordinates (some call it absolute position) browser (IE, Firefox, etc.) compatible.

This is where prototype (download @ www.prototypejs.org) comes in handy!

- create a html file like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<title>Remorse.nl get mouse coordinates</title>

	</head>
	<body>
		<div id="debug" style="position:absolute;left:0px;top:200px;width:200px;border:1px solid #000;height:20px;"></div>
	</body>
</html>

- download prototype js from www.prototypejs.org
- place the prototype.js in the same directory as your .html file
- add a link to your html file prototype in your title:

-add this under your link to prototype:


- it now look like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<title>Remorse.nl get mouse coordinates</title>
		<script type="text/javascript" src="prototype.js" ></script>

		<script type="text/javascript" >
			function getcords(e){
				mouseX = Event.pointerX(e);
				mouseY = Event.pointerY(e);
				//for testing put the mouse cords in a div for testing purposes
				$('debug').innerHTML = 'mouseX:' + mouseX + '-- mouseY:' + mouseY;
			}

			Event.observe(document, 'mousemove', getcords);
		</script>	

	</head>
	<body>
		<div id="debug" style="position:absolute;left:0px;top:200px;width:200px;border:1px solid #000;height:20px;"></div>
	</body>
</html>

- javascript explained:

This prototype peace of code is a event listener, that means that is listen to a certain event.
The object that is listens to is the window object, the event to look for is mousemove and the
function to execute when this event occurs is getcords.
The function that gets executed will automaticly sets a parameter for the function (e).
(Some event tutorial will follow this one)

Event.observe(document, 'mousemove', getcords);

The function getcords has an event parameter automaticly assigned by prototype.
Get the Event.pointerX(e) and Y where the mouse coordinates are stored and put it in a variable.
For showing that it works i inserted a div with the id debug and change de innerHTML of
the div with some data.

function getcords(e){
	mouseX = Event.pointerX(e);
	mouseY = Event.pointerY(e);
	//for testing put the mouse cords in a div for testing purposes
	$('debug').innerHTML = 'mouseX:' + mouseX + '-- mouseY:' + mouseY;
}

That easy!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Furl
  • LinkedIn
  • StumbleUpon
  • Technorati
  • TwitThis
  • NuJIJ