JavaScript Alert Box

Also see the HTML5 <dialog> tag.

The JavaScript alert box is useful for alerting your users to something important. When a JavaScript alert box is triggered, a small box will pop up and display the text that you specify in your JavaScript code.

You create a JavaScript alert box by calling the built-in JavaScript alert() function. All you need to do is pass your message to this function.

JavaScript Alert: onClick

You can place the JavaScript alert() function directly into a button element, then use the onClick event to trigger it. Like this:

JavaScript Alert: Before Page Loads

The above example uses the JavaScript onClick event to trigger the alert box. This example, on the other hand, loads automatically as the page is loading. By placing the code by itself (i.e. not within a link/button), this will automatically trigger the alert box as soon as the page is loading.

The alert will popup as the browser renders the code. Therefore, if you place the code within the <head> tags, your alert box will popup before the HTML elements are displayed. On the other hand, if you call your alert() function within the <body> tags, users will be able to see any HTML elements that have been rendered prior to the alert box code.

View Example

JavaScript Alert: After Page Loads

If you prefer to have the full page visible while the user reads the alert box message, use the onLoad event.

To do this, place a function in the document's <head>, then trigger it using the onLoad attribute in the document's <body> tag.

View Example

JavaScript Alert: Within Another Function

The most common use for the JavaScript alert is to call it from within a function that does something else. The alert simply draws the user's attention to something that the function has done (or detected).

In the above example, if you choose anything but Home, you'll see a JavaScript alert.

HTML <dialog> Element

Also see the HTML <dialog> element, which allows you to do things like, create a dialog box, inspector, window, etc.