Development
Simplest JavaScript to Open Popup Window from Plain Text
You can use JavaScript to create popup windows. Popup windows are different to simply opening a new browser window.
If you only want to open a new browser window you can add the target=”_blank” attribute within your tag. Popup windows however, are more powerful. Using JavaScript’s window.open() method, you can determine what the window looks like (i.e. size, whether it has scrollbars, status bars etc) and also determine it’s position on the screen.
However you can do the same (creating pop windows) using buttons. I’ve already described that here.
Basic JavaScript to Generate a popup window
Here is the simplest JavaScript for generating a pop up window:
// Popup window code
function newPopup(url) {
popupWindow = window.open(
url,'popUpWindow','height=500,width=500,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,
location=no,directories=no,status=yes')
}
<a href=”JavaScript:newPopup(‘http://www.google.com‘);”>Open a popup window
This will result in:
// Popup window code
function newPopup(url) {
popupWindow = window.open( url,'popUpWindow','height=300,width=500,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
Open a popup window
Where:
– Red are width and height of the popup window.
– Purple are the optional attributes (change to “no” to turn off those attributes).
– Blue is the actual link to be opened in the popup.
– Black (bold) is the text which is visible to user.
Automatically center your popup
Similarly if you want to automatically position your window in the center of the users’ screen use the following code. The JavaScript code will detect the screen size (as each user could have a different screen size), then position the popup window in the center.
var popupWindow = null;
function centeredPopup(url,winName,w,h,scroll){
LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
settings =
'height=' h ',width=' w ',top=' TopPosition ',left=' LeftPosition ',scrollbars=' scroll ',resizable'
popupWindow = window.open(url,winName,settings)
}
<a href=”site-url-here” onclick=”centeredPopup(this.href,’myWindow’,’500‘,’300‘,’yes‘);return false”>Centered Popup
This results in:
var popupWindow = null;
function centeredPopup(url,winName,w,h,scroll){
LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
settings =
'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
popupWindow = window.open(url,winName,settings)
}
Where:
– Red are width and height of the popup window respectively.
– Purple is the attribute for the scrollbars in the popup. (Change to “no” to disable scrollbars)
– Blue is the actual link to be opened in the popup.
– Black (bold) is the text which is visible to user.