Previous Page
Next Page

Alerting the User

One of the main uses of JavaScript is to provide feedback to people browsing your site. You can create an alert window that pops up and gives users the vitally important information that they need to know about your page.

In user interface design, less is generally more. For example, you could get the user's attention with loud alarm sirens and big animated banners, but that would be just a bit over the top. Instead, Scripts 2.5 (HTML, which just calls the external script) and 2.6 (JavaScript) show how to create a nice, tasteful alert window. Now you know why we're writers, not designers.

Script 2.5. The HTML for this example includes <script> and <noscript> tags.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="">
     <title>My JavaScript page</title>
     <script language="Javascript" type="text/javascript" src="script04.js">
<body bgcolor="#FFFFFF">
     <h2>This page requires JavaScript.</h2>

Script 2.6. Alert dialog boxes help you communicate with the user.

alert("Welcome to my JavaScript page!");

To alert a user:

  • alert("Welcome to my JavaScript page!");

    Yes, that's all there is to it, as shown in Figure 2.3. Just put the text that you want to have appear within the alert() method in straight quotes.

    Figure 2.3. This script only puts up one dialog box; the four shown are examples of how the dialog box looks in, from top to bottom, Safari for Mac OS X; Microsoft Internet Explorer 6; Microsoft Internet Explorer 7; and Firefox 1.5 on Mac OS X.


  • In most JavaScript alert boxes, you'll see some indication telling the user that the alert box was put up by a JavaScript command. This is a security feature to keep unscrupulous scripters from fooling hapless users. You can't code around this. On Safari for Mac OS X, for example, it shows the URL of the site that opened the alert, as shown in Figure 2.3. Firefox on both Windows and Mac does the same thing. In Internet Explorer 6, the window title is "Microsoft Internet Explorer." Internet Explorer 7 says "Windows Internet Explorer," an interesting bit of rebranding.

  • You'll also see the <noscript> tag used here. On non-JavaScript browsers (older browsers and browsers with JavaScript turned off), a message appears saying that this page requires JavaScript.

Previous Page
Next Page