jQuery

How to find mouse position relative to element with jQuery

In this tutorial, we are going to see how to find mouse position relative to element with jQuery. You can simply use jQuery’s event.pageX and event.pageY with the method offset() of jQuery to get the position of the mouse relative to an element. Here is an example:
 

How to find mouse position relative to element with jQuery
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>How to find mouse position relative to element</title>
		<style type="text/css">
			#myDiv{
				border: 1px solid black;
				background: gray;
				width:300px;
				height:200px;
			}
		</style>
		<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("#myDiv").mousemove(function(event){            
					var X = event.pageX - $(this).offset().left;
					var Y = event.pageY - $(this).offset().top;
					$(".cordn").text("(" + X + "," + Y + ")");
				});
			});
		</script>
	</head>
	<body>
		<div id="myDiv"></div>
		<p>The coordinates of the mouse relative to the DIV block are: <b class="cordn"></b></p>
	</body>
</html>
Result

The coordinates of the mouse relative to the DIV block are:

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *