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!

JavaScript Interview Coming Up?
Subscribe to our newsletter and download the Ultimate JavaScript interview questions and answers collection right now!
In order to get you prepared for your next JavaScript interview, we have compiled a huge list of relevant questions and their respective answers. Besides studying them online you may download the eBook in PDF format!
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

Methods for popping up boxes

In Javascript there are three kinds of popup boxes:

Let’s take a closer look at each one of them.


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:

Alert Box using Javascript


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:

Confirm Box using Javascript


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:

Prompt Box using Javascript

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
Exit mobile version