Duck
Duck

Reputation: 36003

Getting the coordinates where the browser screen is

I would like to open a new window using javascript and window.open but my idea is to open that window, a small one, on the horizontal and vertical center of the current window.

For simplicity, suppose I have a screen that is 1024x768 and I want to display a 200x100 little window on front of that. So, I need that little window to be centered at (512,384) that is the center of (1024,768).

Something like this:

enter image description here

I am using this code to discover the current coordinates:

var x = window.screenX;
var y = window.screenY;
... proceed to window.open...

but this produces a window that is like this

enter image description here

and because I have 2 monitors, when the browser is on monitor 2 this produces a little window positioned on the upper corner of the first monitor.

Is there a way to get the right coordinates?

Upvotes: 3

Views: 378

Answers (1)

nanobar
nanobar

Reputation: 66405

You can use innerWidth and innerHeight of the window to centre it:

const popupWidth = 200;
const popupHeight = 100;
const popupTop = (window.innerHeight / 2) - (popupHeight / 2);
const popupLeft = (window.innerWidth / 2) - (popupWidth / 2);

window.open('https://google.com', 'Google Search', `width=${popupWidth},height=${popupHeight},top=${popupTop},left=${popupLeft}`);

Note: I've used an ES6 string there just for simplicity.

PS I just noticed someone posted a link to the same question with the same kind of answers - this does work, so if it doesn't please explain how it isn't and what browser you're using!

Upvotes: 4

Related Questions