Sunday, August 21, 2016

Using Javascript window.open method

In this article I will show how to use window.open() method of Javascript
to open a new window from a web page.

Let us consider you want to open a window on click of an anchor tag as
following :

HTML Code (.aspx) :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function openWindow() {
            window.open("http://www.google.com", "myWindow", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
        }
        
    </script>
</head>
<body>
    <form id="form1" runat="server">
      <div>
        <a href="#" onclick="openWindow();">Pop Up</a
      </div>
    </form>
</body>
</html>

Normal syntax is window.open(URL, WindowName, Window Features).
Actually following four parameters are allowed :

(1) URL :
This specifies the URL of the page to be opened. 

If the value is blank as below, it will open a blank window

 window.open("""myWindow""toolbar=yes,scrollbars=yes,resizable=yes,top=500,
left=500,width=400,height=400");

If the web page is in the same project only file name is required and no need to
specify the full URL as :

window.open("Default.aspx""myWindow""toolbar=yes,scrollbars=yes,resizable=yes,
top=500,left=500,width=400,height=400");

(2) Window Name :
This specifies the window name or target attributes which are :

_blank :
This is the default value if nothing is specified. It will open the URL
into a new window.
_parent :
In this case URL is loaded into the parent frame.
_self :
In this case URL replaces the current page.
_top :
In this case URL replaces any framesets.

For eg :

  window.open("http://www.google.com""_parent""toolbar=yes,scrollbars=yes,
resizable=yes,top=500,left=500,width=400,height=400");

This will be opened in the parent window.

(3) Window Features :
This specifies various features of the pop up window separated by comma
and without white spaces. 

We can specify following features with yes/no value :
fullscreen, channelmode, directories, menubar, location, resizable, scrollbars,
status, titlebar, toolbar.

And can specify pixel values for the following :
top, width, height, left

(3) replace :
This specifies whether in history a new entry is required for the URL or  replaces
the current entry in the history

If it is true, URL replaces the current entry in the history and if it is
false, a new entry is created in the history.

Note : All parameters are optional.

In HTML code, we can see that href value of the anchor tag is specified as "#".
We can also specify with void value as :

 <a href="javascript:void(0);" onclick="openWindow();">Pop Up</a

No comments:

Post a Comment