jQuery get mouse position within an element jQuery get mouse position within an element jquery jquery

jQuery get mouse position within an element


One way is to use the jQuery offset method to translate the event.pageX and event.pageY coordinates from the event into a mouse position relative to the parent. Here's an example for future reference:

$("#something").click(function(e){   var parentOffset = $(this).parent().offset();    //or $(this).offset(); if you really just want the current element's offset   var relX = e.pageX - parentOffset.left;   var relY = e.pageY - parentOffset.top;});


To get the position of click relative to current clicked element
Use this code

$("#specialElement").click(function(e){    var x = e.pageX - this.offsetLeft;    var y = e.pageY - this.offsetTop;}); 


I use this piece of code, its quite nice :)

    <script language="javascript" src="http://code.jquery.com/jquery-1.4.1.js" type="text/javascript"></script><script language="javascript">$(document).ready(function(){    $(".div_container").mousemove(function(e){        var parentOffset = $(this).parent().offset();        var relativeXPosition = (e.pageX - parentOffset.left); //offset -> method allows you to retrieve the current position of an element 'relative' to the document        var relativeYPosition = (e.pageY - parentOffset.top);        $("#header2").html("<p><strong>X-Position: </strong>"+relativeXPosition+" | <strong>Y-Position: </strong>"+relativeYPosition+"</p>")    }).mouseout(function(){        $("#header2").html("<p><strong>X-Position: </strong>"+relativeXPosition+" | <strong>Y-Position: </strong>"+relativeYPosition+"</p>")    });});</script>