window.screenX is being calculated using all monitors, how can I get the x position of the window in the current monitor

Viewed 66

The following code gets some properties of the monitor, window size and position. My issue is that window.screenX is being calculated by the wrong monitor.

As I have three monitors, if I put the window to the left of my left monitor it returns around -1920px as it is using the middle monitor as a center point, I want this to return zero. Is there any way to return a windows X position based on the current monitor that the window is in?

let windowWidth
let windowHeight
let screenX
let screenY
let monitorWidth
let monitorHeight

window.addEventListener('resize', function() {
  onResize()
});

setInterval(() => {
  onResize()
}, 1000)

function onResize() {
  windowWidth = window.innerWidth
  windowHeight = window.innerHeight
  screenX = window.screenX
  screenY = window.screenY
  monitorWidth = window.screen.availWidth
  monitorHeight = window.screen.availHeight

  document.getElementById("windowWidth").innerHTML = 'windowWidth : ' + windowWidth;
  document.getElementById("windowHeight").innerHTML = 'windowHeight : ' + windowHeight;
  document.getElementById("screenX").innerHTML = 'screenX : ' + screenX;
  document.getElementById("screenY").innerHTML = 'screenY : ' + screenY;
  document.getElementById("monitorWidth").innerHTML = 'monitorWidth : ' + monitorWidth;
  document.getElementById("monitorHeight").innerHTML = 'monitorHeight : ' + monitorHeight;
}
<div id="windowWidth"></div>
<div id="windowHeight"></div>
<div id="screenX"></div>
<div id="screenY"></div>
<div id="monitorWidth"></div>
<div id="monitorHeight"></div>

1 Answers

Use CSS for viewport adjustements - no need for javascript.

Example:

/* IF VIEWPORT IS SMALLER THAN 510 PX */
@media only screen and (max-width : 510px) {
div.this_wrapper{
max-width: 320px;
}
}
Related