How can we center a popup window opened via javascript window.open function on the center of screen variable to the currently selected screen resolution ?
SINGLE/DUAL MONITOR FUNCTION (credit to http://www.xtf.dk - thank you!)
UPDATE: It will also work on windows that aren't maxed out to the screen's width and height now thanks to #Frost!
If you're on dual monitor, the window will center horizontally, but not vertically... use this function to account for that.
const popupCenter = ({url, title, w, h}) => {
// Fixes dual-screen position Most browsers Firefox
const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;
const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
const systemZoom = width / window.screen.availWidth;
const left = (width - w) / 2 / systemZoom + dualScreenLeft
const top = (height - h) / 2 / systemZoom + dualScreenTop
const newWindow = window.open(url, title,
`
scrollbars=yes,
width=${w / systemZoom},
height=${h / systemZoom},
top=${top},
left=${left}
`
)
if (window.focus) newWindow.focus();
}
Usage Example:
popupCenter({url: 'http://www.xtf.dk', title: 'xtf', w: 900, h: 500});
CREDIT GOES TO: http://www.xtf.dk/2011/08/center-new-popup-window-even-on.html (I wanted to just link out to this page but just in case this website goes down the code is here on SO.)
try it like this:
function popupwindow(url, title, w, h) {
var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}
Due to the complexity of determining the center of the current screen in a multi-monitor setup, an easier option is to center the pop-up over the parent window. Simply pass the parent window as another parameter:
function popupWindow(url, windowName, win, w, h) {
const y = win.top.outerHeight / 2 + win.top.screenY - ( h / 2);
const x = win.top.outerWidth / 2 + win.top.screenX - ( w / 2);
return win.open(url, windowName, `toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=${w}, height=${h}, top=${y}, left=${x}`);
}
Implementation:
popupWindow('google.com', 'test', window, 200, 100);
Source: http://www.nigraphic.com/blog/java-script/how-open-new-window-popup-center-screen
function PopupCenter(pageURL, title,w,h) {
var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
return targetWin;
}
If you want to center it on the frame you are currently in, I would recommend this function:
function popupwindow(url, title, w, h) {
var y = window.outerHeight / 2 + window.screenY - ( h / 2)
var x = window.outerWidth / 2 + window.screenX - ( w / 2)
return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + y + ', left=' + x);
}
Similar to Crazy Tim's answer, but doesn't use window.top. This way, it will work even if the window is embedded in an iframe from a different domain.
It works very well in Firefox.
Just change the top variable to any other name and try again
var w = 200;
var h = 200;
var left = Number((screen.width/2)-(w/2));
var tops = Number((screen.height/2)-(h/2));
window.open("templates/sales/index.php?go=new_sale", '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+tops+', left='+left);
My recommendation is to use top location 33% or 25% from remaining space, and not 50% as other examples posted here,
mainly because of the window header,
which look better and more comfort to the user,
complete code:
<script language="javascript" type="text/javascript">
function OpenPopupCenter(pageURL, title, w, h) {
var left = (screen.width - w) / 2;
var top = (screen.height - h) / 4; // for 25% - devide by 4 | for 33% - devide by 3
var targetWin = window.open(pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
}
</script>
</head>
<body>
<button onclick="OpenPopupCenter('http://www.google.com', 'TEST!?', 800, 600);">click on me</button>
</body>
</html>
check out this line:
var top = (screen.height - h) / 4; // for 25% - devide by 4 | for 33% - devide by 3
Facebook use the following algorithm to position their login popup window:
function PopupCenter(url, title, w, h) {
var userAgent = navigator.userAgent,
mobile = function() {
return /\b(iPhone|iP[ao]d)/.test(userAgent) ||
/\b(iP[ao]d)/.test(userAgent) ||
/Android/i.test(userAgent) ||
/Mobile/i.test(userAgent);
},
screenX = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft,
screenY = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop,
outerWidth = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.documentElement.clientWidth,
outerHeight = typeof window.outerHeight != 'undefined' ? window.outerHeight : document.documentElement.clientHeight - 22,
targetWidth = mobile() ? null : w,
targetHeight = mobile() ? null : h,
V = screenX < 0 ? window.screen.width + screenX : screenX,
left = parseInt(V + (outerWidth - targetWidth) / 2, 10),
right = parseInt(screenY + (outerHeight - targetHeight) / 2.5, 10),
features = [];
if (targetWidth !== null) {
features.push('width=' + targetWidth);
}
if (targetHeight !== null) {
features.push('height=' + targetHeight);
}
features.push('left=' + left);
features.push('top=' + right);
features.push('scrollbars=1');
var newWindow = window.open(url, title, features.join(','));
if (window.focus) {
newWindow.focus();
}
return newWindow;
}
You can use css to do it, just give the following properties to the element to be placed in the center of the popup
element{
position:fixed;
left: 50%;
top: 50%;
-ms-transform: translate(-50%,-50%);
-moz-transform:translate(-50%,-50%);
-webkit-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
My version with ES6 JavaScript.
Works well on Chrome and Chromium with dual screen setup.
function openCenteredWindow({url, width, height}) {
const pos = {
x: (screen.width / 2) - (width / 2),
y: (screen.height/2) - (height / 2)
};
const features = `width=${width} height=${height} left=${pos.x} top=${pos.y}`;
return window.open(url, '_blank', features);
}
Example
openCenteredWindow({
url: 'https://stackoverflow.com/',
width: 500,
height: 600
}).focus();
(this was posted in 2020)
An extension to CrazyTim's answer
You can also set the width to a percentage (or a ratio) for a dynamic size.
Absolute size is still accepted.
function popupWindow(url, title, w='75%', h='16:9', opts){
// sort options
let options = [];
if(typeof opts === 'object'){
Object.keys(opts).forEach(function(value, key){
if(value === true){value = 'yes';}else if(value === false){value = 'no';}
options.push(`${key}=${value}`);
});
if(options.length){options = ','+options.join(',');}
else{options = '';}
}else if(Array.isArray(opts)){
options = ','+opts.join(',');
}else if(typeof opts === 'string'){
options = ','+opts;
}else{options = '';}
// add most vars to local object (to shorten names)
let size = {w: w, h: h};
let win = {w: {i: window.top.innerWidth, o: window.top.outerWidth}, h: {i: window.top.innerHeight, o: window.top.outerHeight}, x: window.top.screenX || window.top.screenLeft, y: window.top.screenY || window.top.screenTop}
// set window size if percent
if(typeof size.w === 'string' && size.w.endsWith('%')){size.w = Number(size.w.replace(/%$/, ''))*win.w.o/100;}
if(typeof size.h === 'string' && size.h.endsWith('%')){size.h = Number(size.h.replace(/%$/, ''))*win.h.o/100;}
// set window size if ratio
if(typeof size.w === 'string' && size.w.includes(':')){
size.w = size.w.split(':', 2);
if(win.w.o < win.h.o){
// if height is bigger than width, reverse ratio
size.w = Number(size.h)*Number(size.w[1])/Number(size.w[0]);
}else{size.w = Number(size.h)*Number(size.w[0])/Number(size.w[1]);}
}
if(typeof size.h === 'string' && size.h.includes(':')){
size.h = size.h.split(':', 2);
if(win.w.o < win.h.o){
// if height is bigger than width, reverse ratio
size.h = Number(size.w)*Number(size.h[0])/Number(size.h[1]);
}else{size.h = Number(size.w)*Number(size.h[1])/Number(size.h[0]);}
}
// force window size to type number
if(typeof size.w === 'string'){size.w = Number(size.w);}
if(typeof size.h === 'string'){size.h = Number(size.h);}
// keep popup window within padding of window size
if(size.w > win.w.i-50){size.w = win.w.i-50;}
if(size.h > win.h.i-50){size.h = win.h.i-50;}
// do math
const x = win.w.o / 2 + win.x - (size.w / 2);
const y = win.h.o / 2 + win.y - (size.h / 2);
return window.open(url, title, `width=${size.w},height=${size.h},left=${x},top=${y}${options}`);
}
usage:
// width and height are optional (defaults: width = '75%' height = '16:9')
popupWindow('https://www.google.com', 'Title', '75%', '16:9', {/* options (optional) */});
// options can be an object, array, or string
// example: object (only in object, true/false get replaced with 'yes'/'no')
const options = {scrollbars: false, resizable: true};
// example: array
const options = ['scrollbars=no', 'resizable=yes'];
// example: string (same as window.open() string)
const options = 'scrollbars=no,resizable=yes';
Here is an alternate version of the aforementioned solution...
const openPopupCenter = (url, title, w, h) => {
const getSpecs = (w, h, top, left) => {
return `scrollbars=yes, width=${w}, height=${h}, top=${top}, left=${left}`;
};
const getFirstNumber = (potentialNumbers) => {
for(let i = 0; i < potentialNumbers.length; i++) {
const value = potentialNumbers[i];
if (typeof value === 'number') {
return value;
}
}
};
// Fixes dual-screen position
// Most browsers use window.screenLeft
// Firefox uses screen.left
const dualScreenLeft = getFirstNumber([window.screenLeft, screen.left]);
const dualScreenTop = getFirstNumber([window.screenTop, screen.top]);
const width = getFirstNumber([window.innerWidth, document.documentElement.clientWidth, screen.width]);
const height = getFirstNumber([window.innerHeight, document.documentElement.clientHeight, screen.height]);
const left = ((width / 2) - (w / 2)) + dualScreenLeft;
const top = ((height / 2) - (h / 2)) + dualScreenTop;
const newWindow = window.open(url, title, getSpecs(w, h, top, left));
// Puts focus on the newWindow
if (window.focus) {
newWindow.focus();
}
return newWindow;
}
The accepted solution does not work unless the browser takes up the full screen,
This seems to always work
const popupCenterScreen = (url, title, w, h, focus) => {
const top = (screen.height - h) / 4, left = (screen.width - w) / 2;
const popup = window.open(url, title, `scrollbars=yes,width=${w},height=${h},top=${top},left=${left}`);
if (focus === true && window.focus) popup.focus();
return popup;
}
Impl:
some.function.call({data: ''})
.then(result =>
popupCenterScreen(
result.data.url,
result.data.title,
result.data.width,
result.data.height,
true));
function fnPopUpWindow(pageId) {
popupwindow("hellowWorld.php?id="+pageId, "printViewer", "500", "300");
}
function popupwindow(url, title, w, h) {
var left = Math.round((screen.width/2)-(w/2));
var top = Math.round((screen.height/2)-(h/2));
return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, '
+ 'menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=' + w
+ ', height=' + h + ', top=' + top + ', left=' + left);
}
Print Me
Note: you have to use Math.round for getting the exact integer of width and height.
This hybrid solution worked for me, both on single and dual screen setup
function popupCenter (url, title, w, h) {
// Fixes dual-screen position Most browsers Firefox
const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;
const left = (window.screen.width/2)-(w/2) + dualScreenLeft;
const top = (window.screen.height/2)-(h/2) + dualScreenTop;
return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}
Based on Facebook's but uses a media query rather than user agent regex to calc if there is enough room (with some space) for the popup, otherwise goes full screen. Tbh popups on mobile open as new tabs anyway.
function popupCenter(url, title, w, h) {
const hasSpace = window.matchMedia(`(min-width: ${w + 20}px) and (min-height: ${h + 20}px)`).matches;
const isDef = v => typeof v !== 'undefined';
const screenX = isDef(window.screenX) ? window.screenX : window.screenLeft;
const screenY = isDef(window.screenY) ? window.screenY : window.screenTop;
const outerWidth = isDef(window.outerWidth) ? window.outerWidth : document.documentElement.clientWidth;
const outerHeight = isDef(window.outerHeight) ? window.outerHeight : document.documentElement.clientHeight - 22;
const targetWidth = hasSpace ? w : null;
const targetHeight = hasSpace ? h : null;
const V = screenX < 0 ? window.screen.width + screenX : screenX;
const left = parseInt(V + (outerWidth - targetWidth) / 2, 10);
const right = parseInt(screenY + (outerHeight - targetHeight) / 2.5, 10);
const features = [];
if (targetWidth !== null) {
features.push(`width=${targetWidth}`);
}
if (targetHeight !== null) {
features.push(`height=${targetHeight}`);
}
features.push(`left=${left}`);
features.push(`top=${right}`);
features.push('scrollbars=1');
const newWindow = window.open(url, title, features.join(','));
if (window.focus) {
newWindow.focus();
}
return newWindow;
}
I had an issue with centering a popup window in the external monitor and window.screenX and window.screenY were negative values (-1920, -1200) respectively. I have tried all the above of the suggested solutions and they worked well in primary monitors. I wanted to leave
200 px margin for left and right
150 px margin for top and bottom
Here is what worked for me:
function createPopupWindow(url) {
var height = screen.height;
var width = screen.width;
var left, top, win;
if (width > 1050) {
width = width - 200;
} else {
width = 850;
}
if (height > 850) {
height = height - 150;
} else {
height = 700;
}
if (window.screenX < 0) {
left = (window.screenX - width) / 2;
} else {
left = (screen.width - width) / 2;
}
if (window.screenY < 0) {
top = (window.screenY + height) / 4;
} else {
top = (screen.height - height) / 4;
}
win=window.open( url,"myTarget", "width="+width+", height="+height+",left="+left+",top="+top+"menubar=no, status=no, location=no, resizable=yes, scrollbars=yes");
if (win.focus) {
win.focus();
}
}
This would work out based on your screen size
<html>
<body>
<button onclick="openfunc()">Click here to open window at center</button>
<script>
function openfunc() {
windowWidth = 800;
windowHeight = 720;
var left = (screen.width - windowWidth) / 2;
var top = (screen.height - windowHeight) / 4;
var myWindow = window.open("https://www.google.com",'_blank','width=' + windowWidth + ', height=' + windowHeight + ', top=' + top + ', left=' + left);
}
</script>
</body>
</html>
.center{
left: 50%;
max-width: 350px;
padding: 15px;
text-align:center;
position: relative;
transform: translateX(-50%);
-moz-transform: translateX(-50%);
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
}
Related
I want to open my application page on the second screen using Javascript. I got an example from one of the answers to this question. The example works well, if I have my parent application on the right screen, it opens the window on left. But it does not work if my parent screen is on left screen.
What I want is, I want to open the window on other screen to my parent page screen. This is how the example looks like.
function PopupCenter(url, title, w, h, opts) {
var _innerOpts = '';
if(opts !== null && typeof opts === 'object' ){
for (var p in opts ) {
if (opts.hasOwnProperty(p)) {
_innerOpts += p + '=' + opts[p] + ',';
}
}
}
// Fixes dual-screen position, Most browsers, Firefox
var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;
console.log('dualScreenLeft' + dualScreenLeft);
console.log('dualScreenTop' + dualScreenTop);
var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
console.log('wigth' + width);
console.log('height' + height);
var left = ((width / 2) - (w / 2)) + dualScreenLeft;
var top = ((height / 2) - (h / 2)) + dualScreenTop;
console.log('calculated left ' + left);
console.log('calcualted top ' + top);
var newWindow = window.open(url, title, _innerOpts + ' width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
// Puts focus on the newWindow
if (window.focus) {
newWindow.focus();
}
};
What I should change in my code so it automatically detects the screen and opens the window on another screen.
I am trying this on Firefox and IE (11).
Please check the following diagram, in the multi-monitor/screen environment, the element position in second screen is the start of (1920,0) (suppose the screen resolution is 1920*1080).
// X,Y X,Y S = Screen, W = Window
// 0,0 ---------- 1920,0 ----------
// | | | --- |
// | | | | W | |
// | S | | --- S |
So, we could get the parent window position first, then compare with the screen width and detect whether it is located on the first or second screen, Then, when we open the popup window, we could set the window left property and open it in another screen.
Please refer to the following code:
<script type="text/javascript">
function OpenWindow() {
PopupCenter("https://www.google.com/", "Google", 900, 500, null);
}
function PopupCenter(url, title, w, h, opts) {
var _innerOpts = '';
if(opts !== null && typeof opts === 'object' ){
for (var p in opts ) {
if (opts.hasOwnProperty(p)) {
_innerOpts += p + '=' + opts[p] + ',';
}
}
}
//get the screen width and height.
var screenwidth = window.screen.width;
var screenheight = window.screen.height;
console.log("screen width: " + screenwidth);
console.log("screen height: " + screenheight);
//get current window position. For Firefox, use ["window.screenX"](https://www.w3schools.com/jsref/prop_win_screenx.asp) and ["window.screenY"](https://www.w3schools.com/jsref/prop_win_screenx.asp)
// Fixes dual-screen position, Most browsers, Firefox
var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;
console.log('dualScreenLeft' + dualScreenLeft);
console.log('dualScreenTop' + dualScreenTop);
//get current window width and height
var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
console.log('current window wigth:' + width);
console.log('current window height:' + height);
var left = 0;
var top = 0;
console.log('calculated left ' + left);
console.log('calcualted top ' + top);
//if parent window located in the second screen. set the popup window left property: from 0 to 1920 (the first screen width)
if (dualScreenLeft >= 1920) {
left = 0;
}
else {
//
left = 1920;
}
var newWindow = window.open(url, title, _innerOpts + ' width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
// Puts focus on the newWindow
if (window.focus()) {
newWindow.focus();
}
};
</script>
<input type="button" value="Open window" onclick="OpenWindow();" />
Hi I used the Popupcenter function which is from neofnd/popupCenter to open the aspx page. The aspx page is opened but buttons in the aspx page doesn't fire, no postback. Does someone tell me how to solve it. Thanks in advance.
There is the code from github
function PopupCenter(url, title, w, h) {
// Fixes dual-screen position Most browsers Firefox
var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;
width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
var left = ((width / 2) - (w / 2)) + dualScreenLeft;
var top = ((height / 2) - (h / 2)) + dualScreenTop;
var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
// Puts focus on the newWindow
if (window.focus) {
newWindow.focus();
}
}
There is my button to open call this function.
Good afternoon
CONTEXT
We are using Pintrest JavaScript SDK to pop a dialog to pin something on Pinterest.
REQUIREMENT
We would like the pop up dialog to appear centered on the screen.
PROBLEM
Currently it's working but the dialog box appears at the wrong place.
CODE
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
$.getScript('https://assets.pinterest.com/js/pinit.js', function () {
var pinObj = {
url: url,
media: ogImg.attr("content")
};
pinObj.description = 'description';
PinUtils.pinOne(pinObj);
QUESTION
Is there a way to make pinOne() method pop the dialog centered on the screen?
Regards,
Martin Ouimet
So it seems like you're referencing this from the Widgets API here.
To answer your question, I don't think there is a way to communicate where to open up the dialog. This would be hard in general because depending on the screen size or even the resolution, it's hard to pin point where "centered" is defined.
Looking at the source code of pinOne
pinOne: function(a) {
if (a.href) {
var b = e.f.parse(a.href, {
url: !0,
media: !0,
description: !0
});
b.url && b.url.match(/^http/i) && b.media && b.media.match(/^http/i) ? (b.description || (e.f.log("&type=config_warning&warning_msg=no_description&href=" + encodeURIComponent(e.d.URL)), b.description = e.d.title), e.w.open(a.href, "pin" + (new Date).getTime(), e.a.pop.base.replace("%dim%", e.a.pop.small))) : (e.f.log("&type=config_error&error_msg=invalid_url&href=" + encodeURIComponent(e.d.URL)), e.f.util.pinAny())
} else a.media ? (a.url || (e.f.log("&type=config_warning&warning_msg=no_url&href=" + encodeURIComponent(e.d.URL)), a.url = e.d.URL), a.description || (e.f.log("&type=config_warning&warning_msg=no_description&href=" + encodeURIComponent(e.d.URL)), a.description = e.d.title), e.f.log("&type=button_pinit_custom"), a.href = e.v.config.pinterest + "/pin/create/button/?guid=" + e.v.guid + "&url=" + encodeURIComponent(a.url) + "&media=" + encodeURIComponent(a.media) + "&description=" + encodeURIComponent(a.description), e.w.open(a.href, "pin" + (new Date).getTime(), e.a.pop.base.replace("%dim%", e.a.pop.small))) : (e.f.log("&type=config_error&error_msg=no_media&href=" + encodeURIComponent(e.d.URL)), e.f.util.pinAny());
a.v && a.v.preventDefault ? a.v.preventDefault() : e.w.event.returnValue = !1
},
The only real customization options you are offered include the url, media, and description. Doesn't really seem there is any way to communicate "centered".
That being said, I think this is simply a limitation of their Widget API. if you are hardcoding a specific pinterest link, you might be able to get away with just creating your own and passing in the windowFeatures. I tried it below and it "kinda" works (prob need to adjust the logic of determining the position.
document.getElementById('pinterest-link').addEventListener('click', function(e) {
var URL = e.target.getAttribute('data-pin-myownlink');
// assuming you want a 450x450 popup
var w = 450;
var h = 450;
// plagiarized from http://www.nigraphic.com/blog/java-script/how-open-new-window-popup-center-screen
var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.availLeft;
var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.availTop;
width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
var left = ((width / 2) - (w / 2)) + dualScreenLeft;
var top = ((height / 2) - (h / 2)) + dualScreenTop;
window.open(URL, "Pinterest Link", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+width+', height='+height+', top='+top+', left='+left);
});
<a id="pinterest-link" href="#" data-pin-myownlink="https://www.pinterest.com/pin/create/button/?guid=Nsp1JckZPYuE-6&url=https%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F&media=https%3A%2F%2Ffarm8.staticflickr.com%2F7027%2F6851755809_df5b2051c9_z.jpg&description=Next%20stop%3A%20Pinterest">Click here</a>
StackOverflow disables popups so here's a jsFiddle
I am having the following javascript which open ups a child window with the sizes and align it int he center of the screen
function PopupCenter(url, title, w, h) {
// Fixes dual-screen position Most browsers Firefox
var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;
var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
var left = ((width / 2) - (w / 2)) + dualScreenLeft;
var top = ((height / 2) - (h / 2)) + dualScreenTop;
var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
// Puts focus on the newWindow
if (window.focus) {
newWindow.focus();
}
var timer = setInterval(checkChild, 500);
function checkChild() {
if (newWindow.closed) {
var message = 'You have aborted the transaction by closing the window !';
var status = 'closed';
paymentResponseDisplay(message,status)
clearInterval(timer);
}
}
window.onbeforeunload = function() {
if(!newWindow.closed){
return "Do you really want to abort this transaction?";
}
}
}
But in safari I am getting
TypeError: undefined is not an object (evaluating 'newWindow.focus')
I am unable to find a fix for this. Can some one help out?
In my case, this problem occurred because I called popup from the ajax result in the Safari.
I received ajax with sync and it worked fine.
window.open() works different on AJAX success
Center a popup window on screen? these don't work in Chrome w/ multimonitor. The "screen" seems to refer to the entire desktop, not just the current window. I want to center the popup window within the browser. How can I do that? Needs to be cross-browser.
Here's a demo (should load Google):
function popupwindow(url, title, w, h) {
wLeft = window.screenLeft ? window.screenLeft : window.screenX;
wTop = window.screenTop ? window.screenTop : window.screenY;
var left = wLeft + (window.innerWidth / 2) - (w / 2);
var top = wTop + (window.innerHeight / 2) - (h / 2);
return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
}
<button onclick="popupwindow('http://www.google.com/', 'hello', 400, 400)">
Click
</button>
Here's my method (requires jQuery):
function OpenWindow(params, width, height, name) {
var screenLeft=0, screenTop=0;
if(!name) name = 'MyWindow';
if(!width) width = 600;
if(!height) height = 600;
var defaultParams = { }
if(typeof window.screenLeft !== 'undefined') {
screenLeft = window.screenLeft;
screenTop = window.screenTop;
} else if(typeof window.screenX !== 'undefined') {
screenLeft = window.screenX;
screenTop = window.screenY;
}
var features_dict = {
toolbar: 'no',
location: 'no',
directories: 'no',
left: screenLeft + ($(window).width() - width) / 2,
top: screenTop + ($(window).height() - height) / 2,
status: 'yes',
menubar: 'no',
scrollbars: 'yes',
resizable: 'no',
width: width,
height: height
};
features_arr = [];
for(var k in features_dict) {
features_arr.push(k+'='+features_dict[k]);
}
features_str = features_arr.join(',')
var qs = '?'+$.param($.extend({}, defaultParams, params));
var win = window.open(qs, name, features_str);
win.focus();
return false;
}
Seems to work in all browsers.
This will center the new popup within the browser window and re-focus if it already exists. If you move the browser window and call the popup again it will just re-center the popup.
JS:
var my_window = null;
function popupwindow(url, title, w, h)
{
var screenLeft=0, screenTop=0;
var windowWidth=0, windowHeight=0;
var newTop=0, newLeft=0;
if (typeof window.screenLeft !== 'undefined')
{
screenLeft = window.screenLeft;
screenTop = window.screenTop;
}
else if(typeof window.screenX !== 'undefined')
{
screenLeft = window.screenX;
screenTop = window.screenY;
}
//console.log(screenLeft + ',' + screenTop);
windowWidth = window.innerWidth;
windowHeight = window.innerHeight;
//console.log(windowWidth + ',' + windowHeight);
newLeft = screenLeft + (windowWidth / 2) - (w / 2);
screenTop + (windowHeight / 2);
if (my_window==null)
{
my_window = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + newTop + ', left=' + newLeft);
}
else
{
if (my_window.closed)
{
my_window = null;
my_window = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + newTop + ', left=' + newLeft);
}
else
{
my_window.moveTo(newLeft,newTop);
}
}
my_window.focus();
return false;
}
HTML:
Login