Page 1 of 1

Mouse coordinates in div

Posted: Tue Feb 14, 2006 6:51 am
by Grim...
I can get the mouse coordinates of the cursor position on the screen like this:

Code: Select all

<script type="text/javascript">
function show_coords(event)
{
	x=event.clientX
	y=event.clientY
	alert("X coords: " + x + ", Y coords: " + y)
}
</script>

<body onmousedown="show_coords(event)">
But I want to know where inside a div block the user is clicking. The top left of the div block will be 0, 0 and scrolling the page won't make any difference.

Any ideas?

Posted: Tue Feb 14, 2006 9:39 am
by Chris Corbyn
With absolute positioning it's trivial:

Code: Select all

<script type="text/javascript">
<!-- Hidey hidey

function updatePosition(e)
{
	if (navigator.appName == 'Netscape')
	{
		xcurs = e.pageX;
		ycurs = e.pageY;
	}
	else
	{
		//IE version
		xcurs = event.clientX;
		ycurs = event.clientY;
	}
	showXY(xcurs, ycurs);
}

function showXY(x, y)
{
	el = document.getElementById('foo');
	
	document.getElementById('x').value = x - parseInt(el.style.left);
	document.getElementById('y').value = y - parseInt(el.style.top);
}


// -->
</script>
<body>
<br />
<br />
<div id="foo" style="position: absolute; top: 120px; left: 27px; width: 300px; height: 100px; border: 1px solid #000000;">
 Test
</div>

<input type="text" name="x" id="x" /> <input type="text" name="y" id="y" />

<script type="text/javascript">
<!-- Hidey hidey ;)

if (document.captureEvents) document.captureEvents(Event.MOUSEMOVE);
document.getElementById('foo').onmousemove = updatePosition;

// -->
</script>
But without setiing the position explicitly I'm not sure it's possible. I seem to remember something about determing the page offset of a node but I can't find any documentation in it so I may be wrong.

Posted: Tue Feb 14, 2006 9:49 am
by Grim...
But wouldn't the 'Y' ref change when someone scrolled down and clicked?

Posted: Tue Feb 14, 2006 10:11 am
by Chris Corbyn
Not with that script I just posted no. The cursor positions are based upon the screen (well, in reality it's just the bit of screen that the browser window occupies).

Posted: Tue Feb 14, 2006 10:34 am
by Grim...
Wikkid!

Cheers :)

Posted: Wed Feb 15, 2006 4:56 am
by Grim...
No, IE still counts wrong if you scroll the page - try making that div huge :(

Posted: Fri Feb 17, 2006 8:58 am
by Grim...
:cry:

Anyone?