How to update mouse location when scrolling with jQuery ?
Last Updated :
01 Aug, 2024
jQuery provides us with an extensive set of MouseEvents that are used to provide information regarding the movements of the mouse pointer. For example, the jQuery mousedown event is emitted when left click is performed over a selected element. To determine the coordinates of the mouse pointer over a selected HTML element, we can simply use the jQuery mousemove event. However, to determine the coordinates of the mouse pointer for a selected element which is being scrolled, we first need to understand how does scroll actually work.
A window object represents a window containing the DOM. The document object points to the DOM which is loaded in the window object. An element represents an object in the document. The viewport is referred to the visible area of a webpage.
The viewport varies with the device on which we are viewing the webpage such as a mobile device, tablet or a computer. The viewport is not an actual HTML element but it is referred as the HTML document which is visible to the user and gets fit into the available space.
In the viewport, every element is associated to scrolling box. Every element within the document that has overflowing content has an associated scrolling box with it. So, whenever the user scrolls, it affects the elements scrolling box and not the entire document. Even the window has an associated scrolling box and it varies depending upon the viewport. So whenever we scroll the entire document, it simply changes whatever we are able to see in the viewport and does not have any effect on the document or the window object itself.
Whenever we perform a scroll, the actual location of the mouse pointer on the document object remains unchanged. So you can simply fetch the relative changes in the position of the mouse pointer within the scrolling box of the element, relative to its last position. This tutorial will demonstrate how to get the relative updated coordinates of the mouse on a scroll using jQuery.
Example: Below is the code example of how to update mouse location when scrolling with jQuery
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>How to Update Mouse Location When Scrolling with jQuery?</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
font-family: 'Arial', sans-serif;
}
.container {
background-color: #ffffff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
padding: 20px;
width: 80%;
max-width: 600px;
text-align: center;
}
h1 {
color: #2f8d46;
margin-bottom: 20px;
}
#scroller {
overflow-y: scroll;
height: 150px;
border: 2px solid #2f8d46;
border-radius: 5px;
padding: 10px;
background-color: #f9f9f9;
}
#coordinates {
font-weight: bold;
color: #555;
}
.content {
margin: 10px 0;
color: #333;
}
</style>
</head>
<body>
<div class="container">
<h1>Hello GeeksForGeeks</h1>
<div id="scroller">
<div>Mouse Coordinates - <span id="coordinates">0, 0</span></div>
<div class="content">
A Computer Science portal for geeks. It contains well-written, well-thought, and well-explained computer science and programming articles, quizzes, and more...
</div>
<div class="content">
A Computer Science portal for geeks. It contains well-written, well-thought, and well-explained computer science and programming articles, quizzes, and more...
</div>
</div>
</div>
<script type="text/javascript">
let xPos = 0;
let yPos = 0;
let lastScrolled = 0;
$(document).ready(function () {
// Track mouse movement
$(document).mousemove(function (event) {
xPos = event.pageX;
yPos = event.pageY;
$("#coordinates").text(`${event.pageX}, ${event.pageY}`);
});
// Update mouse position on scroll
$('#scroller').scroll(function () {
if (lastScrolled !== $('#scroller').scrollTop()) {
yPos -= lastScrolled;
lastScrolled = $('#scroller').scrollTop();
yPos += lastScrolled;
console.log(`New X Pos = ${xPos}, New Y Pos = ${yPos}`);
}
});
});
</script>
</body>
</html>
- Explanation: The CSS overflow property is used to control the behaviour of the contents of an HTML element which is too big to fit into the viewport. We can simply clip the content using
overflow: hidden
or add a scroll functionality to view the content of an element in the viewport using overflow: scroll
as shown in the code. - The jQuery ready() method is used to wait for the webpage to finish loading before executing the rest of the javaScript code.
- The jQuery mousemove() method is used to fetch the X and Y coordinates of the mouse pointer whenever the mouse is moved over a Selected element. We can fetch the coordinates using global Event object as shown in the code.
- The jQuery scroll event is emitted when the user scrolls in the selected HTML element scrolling box. The scroll event works for all elements which have an associated scrolling box including the document property of the window object. The scroll() method triggers the scroll event on a selected HTML element as shown in the code.
- The jQuery scrollTop() method is used to return the vertical scrollbar position for the selected HTML elements scrolling box. This method can also be used to set the position of the vertical scrollbar. When the scrollbar is at the top and the user has not scrolled, the position is 0. In the code, this method is used to calculate the relative position of the mouse pointer on a vertical scroll i.e. when the selected HTML element is only scrolled vertically (Y-Coordinate) and the horizontal position of the mouse pointer (X-Coordinate) is fixed. In this case, the selected HTML element has a horizontal scroll associated with it, then you can use the jQuery scrollLeft() method to calculate the relative position of the mouse pointer on horizontal scroll as well. To have a better understanding of the above concept, refer the output.
Output:

Output
Similar Reads
How to display scroll update when scrolling down the page using jQuery ?
In this article, we will learn to show scroll updates when scrolling down on a webpage. The scroll() event handler can be used to detect any scrolling in the page, but we only need to detect the scrolling down. The scroll down event can be handled using the scroll() and scrollTop() events. HTML DOM
2 min read
How to scroll window using jQuery ?
Given a HTML document and the task is to scroll the document with the help of jQuery. There are two methods to scroll the HTML document window which are discussed below: Approach: Select the document by using selector. Use either of the scrollTop() or scrollTo() method to move the document to that p
2 min read
jQuery UI Sortable scrollSpeed Option
jQuery UI is a web-based technology and consists of various GUI widgets, visual effects, and themes. These features can be implemented using the jQuery, JavaScript Library. jQuery UI is the best tool for building UI interfaces for the webpages. It can also be used to build highly interactive web app
2 min read
How to Make Auto Scrolling with CSS?
Auto scrolling can add a dynamic touch to your web pages which makes them more engaging and interactive. Whether you need a horizontal or vertical scroll, CSS provides a way to achieve this effect smoothly. In this article, we will discuss how to make an auto scrolling effect with CSS. ApproachCreat
2 min read
jQuery UI Sortable scroll Option
jQuery UI is a web-based technology and consists of various GUI widgets, visual effects, and themes. These features can be implemented using the jQuery JavaScript Library. jQuery UI is the best tool for building UI interfaces for webpages. It can also be used to build highly interactive web applicat
2 min read
How to get the Position of mouse pointer in jQuery ?
In this article, we will see how to get the position of the mouse pointer using jQuery. To get the position of mouse pointer, event.pageX, and event.pageY property is used. The event.pageX property is used to find the position of the mouse pointer relative to the left edge of the document. The event
1 min read
jQuery UI Sortable scrollSensitivity Option
jQuery UI is a web-based technology and consists of various GUI widgets, visual effects, and themes. These features can be implemented using the jQuery JavaScript Library. jQuery UI is the best tool for building UI interfaces for the webpages. It can also be used to build highly interactive web appl
2 min read
jQuery UI Draggable scrollSpeed Option
The jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Draggable scrollSpeed Option is used to set the speed at which the window should scroll. This option will not work
1 min read
How to set smooth scrolling to stop at a specific position from the top using jQuery ?
The scrollTop() method in jQuery is used to scroll to a particular portion of the page. Animating this method with the available inbuilt animations can make the scroll smoother. And, subtracting the specified value from it will make the scrolling to stop from the top. Approach: The hash portion of t
2 min read
How to change opacity while scrolling the page?
jQuery is used to control and change the opacity during the scrolling of web page. Create a web pages to change the opacity while scrolling the page. The jQuery scroll function is used to scroll the web page and set opacity of text content. Example: C/C++ Code <!-- HTML code to change the opacity
2 min read