// Pops a window relative to the current window position
function popup(url, winName, xOffset, yOffset) {
var x = (window.screenX || window.screenLeft || 0) + (xOffset || 0);
var y = (window.screenY || window.screenTop || 0) + (yOffset || 0);
return window.open(url, winName, 'top=' +y+ ',left=' +x))
}
Call it like the following and it will open on top of the current window
popup('http://www.google.com', 'my-win');
Or make it slightly offset
popup('http://www.google.com', 'my-win', 30, 30);
The point is that window.screenX/screenLeft give you the position in relationship to the entire desktop, not just the monitor.
window.screen.left would be the ideal candidate to give you the information you need. The problem is that it's set when the page is loaded and the user could move the window to the other monitor.
More research
A final solution to this problem (beyond just offsetting from the current window position) requires knowing the dimensions of the screen that the window is in. Since the screen object doesn't update as the user moves a window around, we need to craft our own way of detecting the current screen resolution. Here's what I came up with
/**
* Finds the screen element for the monitor that the browser window is currently in.
* This is required because window.screen is the screen that the page was originally
* loaded in. This method works even after the window has been moved across monitors.
*
* @param {function} cb The function that will be called (asynchronously) once the screen
* object has been discovered. It will be passed a single argument, the screen object.
*/
function getScreenProps (cb) {
if (!window.frames.testiframe) {
var iframeEl = document.createElement('iframe');
iframeEl.name = 'testiframe';
iframeEl.src = "about:blank";
iframeEl.id = 'iframe-test'
document.body.appendChild(iframeEl);
}
// Callback when the iframe finishes reloading, it will have the
// correct screen object
document.getElementById('iframe-test').onload = function() {
cb( window.frames.testiframe.screen );
delete document.getElementById('iframe-test').onload;
};
// reload the iframe so that the screen object is reloaded
window.frames.testiframe.location.reload();
};
So if you wanted to always open the window at the top left of whatever monitor the window is in, you could use the following:
function openAtTopLeftOfSameMonitor(url, winName) {
getScreenProps(function(scr){
window.open(url, winName, 'top=0,left=' + scr.left);
})
}