By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

JavaScript Popup Windows

How to create a JavaScript Popup Window using a user-made function, triggered by the onclick event of a button.

Created: 2012-02-25 16:28

This tutorial shows how to create a JavaScript Popup Window.

Please keep in mind that popups are annoying to the majority of users. Its also poorly supported in newer browsers, this is largely due to build-in popup blockers and lack of support due to usability issues. Also keep in mind that using popups for ads is a very bad idea, not only will most browsers detect it, its also one of the things that can annoy users the most.

If you just want to open links in a new window, then you might want to consider using the HTML target attribute, and setting its value to _blank instead. But be mindful, its generally annoying to users, so don't do it unless you design alternatives to the browsers build-in open in new tab, open in new window. Etc.

Controlling Window.Open with Parameters

The Window.Open method can take four parameters, these are used to tell how the new window behaves. The list of arguments is as follows:

URLAbsolute Path
FeaturesComma seperated list
Replacetrue or false

The last argument is a comma seperated list of properties, some of these properties are listed below:

dependent0 or 1The window is dependent on the window that opened it, and will close if its parent dose.
heightPixelsSets the height of the new window.
widthPixelsSets the width of the new window.
topPixelsSets the window placement from the left side of the screen.
leftPixelsSets the window placement from the top of the screen.

Creating Popups in JavaScript

Lets create a user-made function that we can call anywhere we want, which will open the Popup when called.

Here is the user made function that we will use in this tutorial.

function myPopup() {"", "MyWindowName", "height=100,width=100,top=10,left=10");

We can then use this script anywhere we want, using one of the event attributes. For simplicity, lets use the onclick event to trigger the function when the user clicks a button element, this can be done with the below HTML.

<button onclick="myPopup();">Either push or don't push!</button>