JavaScript Alert Box
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.
Creating/Triggering a JavaScript Alert
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 - "On Click"
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:
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.
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).
Code
Result:
In the above example, if you choose anything but "Quackit Homepage", you'll see a JavaScript alert.
