What is the best way to retrieve the mouse position relative to the window viewport using JavaScript?

event.pageY retrieves the mouse position in relation to the overall document height (

document.documentElement.offsetHeight
in my understanding).

However, I am curious about how to obtain the mouse position concerning the current viewport, which is

document.documentElement.clientHeight
?

For example, if the browser window's height is 720 pixels, and I scroll down 3 pages while keeping the mouse at the center of the window, the position should be "360", not 1800 (720 x 3 - 720 / 2).

Answer №2

The mouse's horizontal position relative to the viewport can be obtained using the following code:

document.addEventListener('mousemove', event => {
    console.log(event.clientY) // This will give you the desired result     
})

Here is a list of options available:

  • e.clientX/Y: position relative to the viewport
  • e.screenX/Y: position relative to the screen
  • e.pageX/Y: position relative to the page (accounting for scroll)

Feel free to run the snippet below to observe the different positions being updated in real time:

const updateView = (e = {}) =>  document.getElementById('log').innerHTML = `
  <div>
    Relative to screen:<br>
    e.screenX: <b>${e.screenX || '0'}</b><br>
    e.screenY: <b>${e.screenY || '0'}</b>
  </div>
  <div>
    Relative to viewport:<br>
    e.clientX: <b>${e.clientX || '0'}</b><br>
    e.clientY: <b>${e.clientY || '0'}</b>
  </div> 
  <div>
    Relative to page (scroll to see the difference with viewport):<br>
    e.pageX: <b>${e.pageX || '0'}</b><br>
    e.pageY: <b>${e.pageY || '0'}</b>
  </div>
`

document.getElementById('content').innerHTML = `BIG CONTENT `.repeat(300)

document.addEventListener('mousemove', updateView)

updateView()
#log { display:flex;justify-content:center;position:fixed }
#log > div { flex: 1 1 0 }
<div id='log'></div>
<div id='content' style='opacity:.1'></div>

Answer №3

Access the event.clientY attribute to retrieve the mouse coordinates in relation to the browser window (See Compatibility chart).

Answer №4

In a similar scenario, I found myself in need of the cursor's coordinates in relation to the viewport while dealing with a scrollable page.

Other solutions I attempted didn't hold up when the screen was scrolled, performing well only on non-scrollable pages.

After consulting some documentation on https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent, I discovered that when working with a scrollable page, utilizing event.pageX is preferable for obtaining X and Y coordinates relative to the current viewport, even when scrolled.

var pageX = MouseEvent.pageX;

For more information, visit https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX

Answer №5

For those in search of viewport coordinates instead of screen, client, or page coordinates, follow this solution...

const svgElement = document.querySelector('svg');
let svgPoint = svgElement.createSVGPoint();
var cursorPoint =  svgPoint.matrixTransform(svgElement.getScreenCTM().inverse());
svgPoint.viewport_x =  cursorPoint.x
svgPoint.viewport_y =  cursorPoint.y

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for including a header with Apollo Client in a React Native app

In my React Native application, here's how I set up the Apollo client with an upload link: My goal is to include a header with a token value that will be sent with every request. However, I've had trouble finding an example specifically for Reac ...

The markers are refusing to appear on the map, despite the fact that the data is successfully being retrieved from

<?php error_reporting(E_ALL ^ E_DEPRECATED); $conn = mysql_connect("localhost", "root", "root") or die(mysql_error()); mysql_select_db("db_jawandsons") or die(mysql_error()); ?> <html> <head> <meta http ...

Tips for locating a specific property deep within an array and pinpointing its exact location

Is it possible to use JavaScript to locate a property within an array that is nested within another array and return its "path"? Visualize a hierarchical group of nested arrays similar to this example: var bigBox = [ mediumBoxA = [ ...

Using C# to send pictures to a WhatsApp contact

Is it possible to send an image along with a text message to a WhatsApp number through the API? https://api.whatsapp.com/send?phone=15551234567&text=I'm%20interested%20in%20your%20car%20for%20sale I have successfully sent text messages using thi ...

Transfer a loaded object to a different object using Javascript

Starting with the title, I have an initialized object that looks like this "travellerDetails": { "traveller_1": { "Full Name": "", "Gender": "", }, "traveller_2": { "Full Name": "", "G ...

Aggregating and organizing all TypeScript files within the project while preserving the file hierarchy

Looking to utilize a task runner such as Grunt or Gulp to compile TS to JS files in various locations within the project folder. The goal is to ensure that the outputted JS files are placed in the same directory where the project will look for them alongsi ...

What seems to be the issue with the functionality of the done button?

I am currently working on developing a to-do list application where I can add and remove tasks. Adding tasks is functioning correctly, but when it comes to clicking the Done Button, it's not performing as expected. This issue indicates a logical error ...

Performing multiple asynchronous tasks using RxJS by running Array.prototype.map in parallel batches or queues

Imagine having an array of variables, such as: [Sasha, Misha, Caitlyn, ...String] (string[]) with a sizable length of about 10k elements. If you want to run an asynchronous parallel task with these elements, but not all at once like Promise.all, rather in ...

Problem with animated text in CSS

I am facing an issue with the code below. It is supposed to display "Dedicated People" when scrolling down, however, it is not working in my browser. Could it be that I forgot to include a reference in the head section? The code works fine in CodePen, but ...

How can I retrieve data submitted in a POST request on my Node.js server

I'm having trouble sending form data to a node/express server using AJAX. After submitting, I keep getting redirected to a 'Cannot POST /' page. Although I can log the request object on the server side, the data from the form is missing. Wha ...

What is the best way to sort through td attributes in an HTML table?

I am trying to filter the td attribute in my HTML table, but the results are not as expected. My goal is to display the tr data-value attribute that contains the specified value. "My English may not be perfect, please bear with me." function FilterTabl ...

Refreshing the previous tab upon changing tabs in React Navigation TabNavigator

I am currently working with a route structure that looks like this: StackNavigator -StackNavigator -TabNavigator --Tab1 ---Route 1 (Stack) (initial) ---Route 2 (Stack) --Tab2 ---Route 3 (Stack) (initial) ---Route 4 (Stack) The issue I am facing is that ...

Tips for invoking a url with JavaScript and retrieving the response back to JavaScript

I am trying to make a URL call from JavaScript with a single parameter, and the URL should respond to that specific request. Here is an example of the response format: {"success":true, "result": {"token":"4fc5ef2bd77a3","serverTime":1338371883,"expireT ...

Is it possible to select options in AngularJS based on certain criteria?

I created an AngularJS select menu that is currently functioning correctly: <select name="s1" id="s1" multiple="multiple" data-native-menu="false" data-role="none" ng-model="userlistSelect" ng-options="u.userId as u.fi ...

Is it detrimental to my search engine ranking if I utilize CSS display:none?

Imagine having valuable content that is initially hidden with CSS, and then using javascript to reveal it only when the user clicks on certain links. Even users without javascript enabled can access this content by following the links to a new page where i ...

No Backend Detected for Tensorflow.js in Node

I've been attempting to develop a Discord bot that utilizes the @tensorflow-models/qna library, but I've hit a roadblock for the past 4 hours. Every time I run the script below: const qna = require('@tensorflow-models/qna'); (async () ...

Looking for assistance with resizing and repositioning an image within a viewport?

The JSFiddle code can be found at this link - https://jsfiddle.net/pmi2018/smewua0k/211/ Javascript $('#rotate').click(function(e) { updateImage(90, 0) console.log("rotation"); }); $('#zoom-in').click(function() { updateImage(0 ...

The Importance of Selenium Events and Patience

Currently, I am using Selenium to automate some testing for our company's website, but encountering issues along the way. TestItemFromSearch: (driver, part, qty) => { Search.SearchItem(driver, part); driver.findElement(By.id('enterQty ...

Activate fullscreen mode in Krpano on desktop by clicking a button

Is there a way to activate fullscreen mode upon clicking a button? I believe I should use the code: krpano.set(fullscreen,true); Currently, I have an image within a slideshow that includes a play button overlay. Once the button is clicked, the slideshow ...

Steps to dynamically retrieve and incorporate external JavaScript using an Ajax request

Just getting started with Ajax and running into an issue. We have a cart page on our site where users can dynamically add, remove, and update item quantities using Ajax without refreshing the entire page. My problem is that I need to trigger some third-par ...