Any user interaction on a webpage triggers certain events. Since we are looking for the position of the mouse pointer, we will only cover click and mousemove events. The click event occurs whenever a user clicks on an element. The mousemove event is fired whenever the mouse pointer moves within an element.
In the case of both the above events, we will have pageX and pageY properties in the event object. The pageX property will give us horizontal coordinates and the pageY property will give us vertical coordinates. For the sake of simplicity, we are going to get the position of the mouse pointer whenever we click or move anywhere in the document.
You can also go with clientX and clientY properties to get mouse coordinates. But there is a difference between page and client coordinates. The page represents the whole rendered page and that includes the visible area as well as scrolled area in the browser. On the other hand, the client will only give you coordinates based on the visible area in the browser.
In the following example, we will simply display horizontal and vertical coordinates of the mouse pointer on click and movement. Please have a look over the code example and the steps given below.
HTML & CSS