How to get mouse position - relative to an element

I would like to get the mouse position relative to the element the cursor is in.

The following code captures the position in which the mouse is relative to the page.

$( "div" ).mousemove(function( event ) {
var pageCoords = "( " + event.pageX + ", " + event.pageY + " )";
var clientCoords = "( " + event.clientX + ", " + event.clientY + " )";
$( "span:first" ).text( "( event.pageX, event.pageY ) : " + pageCoords );
$( "span:last" ).text( "( event.clientX, event.clientY ) : " + clientCoords );
});

http://api.jquery.com/mousemove/

0
source share
3 answers

Try JSFiddle

You need to include the .js file to use this code: Jquery-2.1.1.js

For relative mouse position, the code is here:

var x,y;
$("#div1").mousemove(function(event) {
    var offset = $(this).offset();
    x = event.pageX- offset.left;
    y = event.pageY- offset.top;
    $("#div1").html("(X: "+x+", Y: "+y+")");
});
+4
source

HTML http://jsfiddle.net/1gzdkg9p/

<div id="result"></div>

JQuery

jQuery(function($) {
    var currentMousePos = { x: -1, y: -1 };
    $(document).mousemove(function(event) {
        currentMousePos.x = event.pageX;
        currentMousePos.y = event.pageY;
        $("#result").html("X: "+currentMousePos.x+"  Y : "+currentMousePos.y);
    });



});
+1
source

Take a look at Fiddle . [Edited]

You need to get the coordinates of the mouse, and then subtract the offset of the element to get the relative value.

HTML:

<div class="test"></div>

JS:

$(document).on('mousemove','.test', function(e){
    var offset = $(this).offset();
    var relativeX = e.pageX - offset.left;
    var relativeY = e.pageY - offset.top;
    var wide = $(this).width();
    var tall = $(this).height();
    var percentX = (relativeX*100)/wide;
    var percentY = (relativeY*100)/tall;
    console.log(percentX+", "+percentY);
});

CSS

.test{
  background-color: #000000;
  width: 50%;
  height: 50px;
  margin-left: 40px;
  margin-top: 20px;
}
0
source

Source: https://habr.com/ru/post/1686910/


All Articles