jQuery missing layerX

Getting the Mouse posi­tion in jQuery is very sim­ple. However, get­ting the posi­tion from within an ele­ment take some extra steps.

Normally, a javascript event such as onmousemove would use event.layerX and event.layerY to get the coor­di­nates of our mouse when it moves.

For jQuery, pageX and pageY will return val­ues from the top left of the page and not the layer. Unless the ele­ment you’re work­ing with is left-​aligned, you need to cal­cu­late the off­set of that ele­ment as well. Not only that (unless there is a bet­ter way to do this) the off­set val­ues returned doesn’t include the off­set val­ues of the par­ent tag.

In this exam­ple, I have two divs.

<div id="frame">
	<div id="content"></div>
</div>

And you can imag­ine that #frame is cen­tered and has padding. Getting #content’s off­set won’t include any­thing out­side of the frame so $(#content).offset().left; would only get you the dis­tance of itself and its parent.

Get your lay­erX for jQuery

For this exam­ple, we are using a known set of divs so we can just write out each div in this script.


$(document).ready(function(){
	$('#canvasForeground').mousemove(function(e){
		var myLayerX = $('#content').offset().left + $('#frame').offset().left;
		var myLayerY = $('#content').offset().top + $('#frame').offset().top;
		var x = 0, y = 0;
		x = e.pageX - myLayerX;
		y = e.pageY - myLayerY;
	});
});

The vari­ables are declared inside the event func­tion to han­dle win­dow resiz­ing. Now were this a more com­pli­cated page and the ele­ment in ques­tion has deeply nested or even dynam­i­cally gen­er­ated, writ­ing our all the par­ent tags wouldn’t nec­es­sar­ily work (or be very effi­cient).* But the approach would remain the same. That’s it!

*stan­dard apol­ogy for poor code writ­ing skills

This entry was posted in Code and tagged , , . Bookmark the permalink.

Comments are closed.