JavaScript Pop-Ups

JavaScript Pop-Ups
JavaScript was designed to add interactivity to web pages, so it's not surprising that it has a several functions to make it simple to collect information from and display it to a user using pop-up boxes. Before we look at these boxes, keep in mind that while these are often the simplest way to collect and display information, they are not necessarily the most attractive or user-friendly. Among other things, pop-ups require the user to press a button to close the window after every message or input – this can get old fast. Also, from a web design viewpoint, you really have very little control over the presentation of information in pop-up boxes. That said, in the right place, and used in moderation, pop-up boxes can be both simple and effective.

There are three types of pop-up boxes – alert, confirm, and prompt. The simplest, and most commonly used pop-up is alert. Alert takes one argument – a message to the user. When a alert box pops up, the user cannot continue until they press the "OK" button. The code for an alert box is simple:

alert("This is an alert")

JavaScript Alert Pop-Up

The confirm box is only slightly more complicated. Like alert, confirm takes one argument – the message. When a confirm box pops up, the user is given a choice of answering using the "OK" or "Cancel" buttons. Unlike alert, confirm has a return value – 0 means the user pressed "Cancel" and 1 means "OK". The code for a confirm box is identical to an alert box except that you want to collect the return value somehow:

save_me=confirm("This is a confirm pop-up")

JavaScript Confirm Dialog Box

Although it is the most complicated of the pop-ups, prompt is still quite simple. Prompt takes two arguments – a message to the user and a default value (or "" if you want no default value.) When the prompt box pops up, the user can enter the requested information and press "OK". There is also a "Cancel" button. The return value is the user's response. If the user cancels the return value is null. If they leave the prompt box empty, the return value will be the empty string (""). You probably want to check for these values and do something special rather than use null or the empty string as their response. The code for an prompt box is:

response=prompt("This is a prompt", "Respond here")

JavaScript Prompt Dialog Box

You can view a demonstration of these pop-up boxes here

Get in the mood for coding with this bopping solar mushroom from Think Geek

This site needs an editor - click to learn more!

You Should Also Read:
JavaScript Basics - User Interaction
Making Simple Decisions in JavaScript
JavaScript articles

Related Articles
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map

Content copyright © 2023 by Julie L Baumler. All rights reserved.
This content was written by Julie L Baumler. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.