Skip to main content

jQuery Get Relative Mouse Position

By Sam Deering

JavaScript

Share:

😳 Ever felt a little embarassed sharing your JavaScript? Let's fix it.

jQuery code snippet to get the relative position of the mouse pointer. The function takes in the element id as a parameter and the current x and y co-ordinates of the mouse pointer. It then returns the relative distances between the mouse’s cursors current position and the specified element.

function rPosition(elementID, mouseX, mouseY) {
  var offset = $('#'+elementID).offset();
  var x = mouseX - offset.left;
  var y = mouseY - offset.top;
  return {'x': x, 'y': y};
}

Example Usage

jQuery(document).ready(function($) {

	//get the current x and y of the mouse pointer
	var X = $('body').offset().left;
	var Y = $('body').offset().top;
	mouseX = ev.pageX - X;
	mouseY = ev.pageY - Y;
	
	//get the relative position to the #eid element on the page
	alert(rPosition('eid',x,y));

});

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

💁‍♀️ Fun Fact: Python was ranked #2 on a recent highest paid coders list. *


🤓 Ok. When did a code editor from Microsoft become kinda cool!?