Skip to content

Instantly share code, notes, and snippets.

@andrewgilmartin
Created February 17, 2009 14:07
Show Gist options
  • Save andrewgilmartin/65748 to your computer and use it in GitHub Desktop.
Save andrewgilmartin/65748 to your computer and use it in GitHub Desktop.
// See http://remorse.nl/weblog/get_the_mousecursor_position_relative_to_an_element_with_prototype/
function relativeEventLocation(event,container){
if ( container == null ) {
container = Event.element(event);
}
//get the position of the container
var containerLeft = Position.page(container)[0];
var containerTop = Position.page(container)[1];
//get the mouse coordinates
mouseX = Event.pointerX(event);
mouseY = Event.pointerY(event);
//calculate the absolute mouse position in the div
horizontalPosition = mouseX - containerLeft;
verticalPosition = mouseY - containerTop;
//use prototypes function to get the dimension
//this is a VERY usefull function because it also checks for borders
containerDimensions = container.getDimensions();
height = containerDimensions.height;
width = containerDimensions.width;
//check if the mouse is out or inside the div
if(horizontalPosition < 0 || verticalPosition < 0 || mouseX > (width + containerLeft) || mouseY > (height + containerTop) ){
return null;
}
return { x: horizontalPosition, y: verticalPosition };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment