Javascript Popup Example
In many cases it is useful to add a popup to your page or website. In Javascript there are ready made methods to do that, or you can create popups manually. Take a look!
Methods for popping up boxes
In Javascript there are three kinds of popup boxes:
- Alert boxes
- Popup boxes
- Confirm boxes
Let’s take a closer look at each one of them.
Alerts
We use alerts to make sure the user has understood some important information about your page. “OK” has to be clicked in order to continue.
It’s used like below:
alert("This is an alert about an important issue!!");
You will have something like this:
Confirm
Confirm boxes are used to get the users’ decision about something. That means that there are two buttons, one “OK” and one “Cancel”. The function returns true if the user clicks “OK” and false if the user clicks “Cancel”.
It is used like this:
var response = confirm("Do you want to leave this page?"); if (response == true) { alert("You might lose unsaved data!"); } else { alert("Glad that you stayed!"); }
Your confirm box will look like below:
Prompts
Prompt boxes are used when we need user’s input about something. One example is to ask for the user’s age before displaying sensitive information. The function returns the input or NULL in case no data is entered. After putting data in the input field, the user has to click “OK” or “Cancel” to continue.
You can put it to use like below:
var age = prompt("Please enter your age", "15+"); if ( age < 13 ) { document.getElementById("demo").innerHTML = "Please ask for permission from your parents or guardian before going on"; }
Here’s how your prompt box will look:
These are the three methods you can use to pop up a box.
Download the source code
This was an example of popups in Javascript.
You can download the full source code of this example here: Popup