Start Working With Browser Windows in JavaScript - How to open a new pop up window using JavaScript
(Page 4 of 5 )
Now, let us try to develop a simple script (JavaScript) to open a new pop up window. Have a look at the following code:
<html>
<head>
<meta name=vs_targetSchema
content="http://schemas.microsoft.com/intellisense/ie5">
<script id="clientEventHandlersJS" language="javascript">
<!--
function openWindowAtCenter(url) {
var myWindow;
var w = 400;
var h = 300;
var l = parseInt((screen.availWidth/2) - (w/2));
var t = parseInt((screen.availHeight/2) - (h/2));
var f = "width=" + w + ",height=" + h +
",status,resizable,left=" + l + ",top=" + t +
",screenX=" + l + ",screenY=" + t;
myWindow = window.open(url, "NewWindow", f);
}
function Button1_onclick() {
openWindowAtCenter(http://www.yahoo.com);
}
//-->
</script>
</head>
<body>
<form id="form1">
<input type="button" value="Show" id="Button1"
name="Button1" onclick="return Button1_onclick()">
</form>
</body>
</html>
This concept is quite different from any of the previous sections. How can we achieve the opening of a new sub-window (or a pop up window)? This is simply possible using the following statement:
window.open(...)
Even though the above statement accepts very few parameters, it has a lot of features embedded within it. It mainly accepts a URL (to open the page in new pop up window), the name of the window and the features of the window as parameters. Let us consider the function defined in the above code:
function openWindowAtCenter(url) {
var myWindow;
var w = 400;
var h = 300;
var l = parseInt((screen.availWidth/2) - (w/2));
var t = parseInt((screen.availHeight/2) - (h/2));
var f = "width=" + w + ",height=" + h +
",status,resizable,left=" + l + ",top=" + t +
",screenX=" + l + ",screenY=" + t;
myWindow = window.open(url, "NewWindow", f);
}
The above function tries to open a window based on the URL you specified as a parameter. Let us go through the list of variables I used in the above function:
W – represents the width of pop up window.
H – represents the height of pop up window.
L – represents the left of pop up window.
T – represents the top of pop up window.
F – represents the features of pop up window.
The last parameter of “window.open” accepts a list of the window's features in the form of a simple string. That is the reason I added all the features to a simple string variable “f” and finally passed it as the last parameter. In fact, there exists a lot more features for opening pop up windows.
Next: A word of caution >>
More JavaScript Articles
More By Jagadish Chaterjee