How to Open a Javascript Pop Up With Fixed Size

By | December 1, 2008

Modern browsers in their default settings are blocking pop up windows. A simple window.open will not open a pop-up as most probably it will be blocked. But what to do if you need to show a special offer or something like this?

I’d suggest you to open a window on user action, e.g. clicking a button or moving mouse. I’ve copied this script from the Internet and successfully using it to enable pop-ups on clicking the links.

<script type=”text/javascript” language=”javascript”>
<!– //
var popWin = null    // use this when referring to pop-up window
var winCount = 0
var winName = “popWin”
function openPopWin(winURL, winWidth, winHeight, winFeatures, winLeft, winTop){
var d_winLeft = 20  // default, pixels from screen left to window left
var d_winTop = 20   // default, pixels from screen top to window top
winName = “popWin” + winCount++ //unique name for each pop-up window
closePopWin()           // close any previously opened pop-up window
if (openPopWin.arguments.length >= 4)  // any additional features?
winFeatures = “,” + winFeatures
else
winFeatures = “”
if (openPopWin.arguments.length == 6)  // location specified
winFeatures += getLocation(winWidth, winHeight, winLeft, winTop)
else
winFeatures += getLocation(winWidth, winHeight, d_winLeft, d_winTop)
popWin = window.open(winURL, winName, “width=” + winWidth
+ “,height=” + winHeight + winFeatures)
}

function closePopWin(){    // close pop-up window if it is open
if (navigator.appName != “Microsoft Internet Explorer”
|| parseInt(navigator.appVersion) >=4) //do not close if early IE
if(popWin != null) if(!popWin.closed) popWin.close()
}

function getLocation(winWidth, winHeight, winLeft, winTop){
return “”
}

function getLocation(winWidth, winHeight, winLeft, winTop){
var winLocation = “”
if (winLeft < 0)
winLeft = screen.width – winWidth + winLeft
if (winTop < 0)
winTop = screen.height – winHeight + winTop
if (winTop == “cen”)
winTop = (screen.height – winHeight)/2 – 20
if (winLeft == “cen”)
winLeft = (screen.width – winWidth)/2
if (winLeft>0 & winTop>0)
winLocation =  “,screenX=” + winLeft + “,left=” + winLeft
+ “,screenY=” + winTop + “,top=” + winTop
else
winLocation = “”
return winLocation
}
//–>
// –>
</script>

Script usage is the following:

onClick=”javascript:openPopWin(‘Your URL’,Width,height,”,pixels from screen left to window left,pixels from screen top to window top)”

This will allow you to open a window and it is not blocked with browsers. If you have a more elegant solution, you’re welcome to post it here.