Javascript

Mouse position - relative to a containing element


February 5, 2008 19:06 by joel

There is something about browser quirks that brings to mind a schoolyard argument. Both sides punching and kicking their way around a meaningless dispute, simply because they're both too stubborn to get along. It may be immature, but it's unfortunately the situation that every JavaScript programmer currently finds themselves in.

I've been doing some work lately with the new MapQuest JavaScript API, which will be officially launched sometime in the next few weeks. The other day I stumbled across a problem that in some situations has a relatively simple solution, but nonetheless seems to be quite difficult to accomplish: discovering the coordinates of a mouse event relative to the containing element.

I'm not going to get into the relative merits and de-merits of the Microsoft AJAX Library. I'll save that for another post. However, since I work with ASP.NET, and the library is automatically included with an ASP.NET AJAX website, I have gotten used to some of the shortcuts that the library provides. Now, I'm sure that there are some JavaScript libraries out there that provide a method for discovering these ellusive coordinates, regardless of the browser or the immediate situation. Unfortunately the Microsoft Library doesn't seem to be one of them. Theoretically, the event.offsetX and event.offsetY values should give you these coordinates. Practically, however, it just doesn't work in a consistent way. This is the solution that I came up with for my problem, and it seems to work fairly well in a lot more situations than just pulling the offset values out of the event object.

function Position(e,ele){
// gotta pull 2 pixels out of the mix in IE, for some reason
var offset = (Sys.Browser.agent == Sys.Browser.InternetExplorer) ? 2 : 0; 
var deShort = document.documentElement;
var lefty = (deShort.scrollLeft ? deShort.scrollLeft : document.body.scrollLeft);
var toppy = (deShort.scrollTop ? deShort.scrollTop : document.body.scrollTop);
var loc = Sys.UI.DomElement.getLocation(ele);
return { y  : e.clientY + toppy - loc.y - offset,  x : e.clientX + lefty - loc.x - offset }
}

So basically all you do is pass your event object and the containing element into this function, and it should return you an object with x and y coordinates, relative to the top left corner of that element. Will I be surprised if you give me a situation that this doesn't work in?? Not at all. Feel free to let me know, though, and I'll try and update with a fix, as the need arises.



Related posts

Add comment


 

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

October 6. 2008 07:34