Created
February 17, 2009 14:07
-
-
Save andrewgilmartin/65748 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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