Open In App

How to update mouse location when scrolling with jQuery ?

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.


Article Tags :