user1937021
user1937021

Reputation: 10771

How to get mouse position - relative to element

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

The following code capture the position where 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/

Upvotes: 3

Views: 16922

Answers (3)

Jarvis Stark
Jarvis Stark

Reputation: 611

Try this JSFiddle

You need to include .js file for using 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+")");
});

Upvotes: 6

Luigi Siri
Luigi Siri

Reputation: 2018

Take a look on this Fiddle. [Edited]

You have to get the coordinates of the mouse and then substract 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;
}

Upvotes: 0

Yatin Mistry
Yatin Mistry

Reputation: 1264

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);
    });



});

Upvotes: 1

Related Questions