A more complex example of interactive dialog boxes
Using these three basic methods (window.alert()
, window.confirm()
, and
window.prompt()
), we can actually create some more "useful" scripts.The
below illustrates how to add a confirmation box to a web page that asks a
user whether he/she really wants to enter the page. If not, the surfer is
taken to Yahoo instead:
<html> <head> <script type="text/javascript"> var stay=confirm("The following site contains appalling material suitable only for webmasters. Please 'ok' to enter, 'cancel' to exit immediately!") if (!stay) window.location="http://www.yahoo.com" </script> </head> <body> Appalling material here </body> </html>
In the above example, clicking "cancel" in the confirmation box will take the surfer to yahoo, and clicking ok will continue with the loading of the "appalling" document.
There are two lines of code above that require explaining:
if (!stay) window.location="http://www.yahoo.com"
Translating the above into pure English, it reads "if the
surfer pressed "cancel", take him to Yahoo. Recall that confirmation boxes
always return either a Boolean value of "true" or "false" to a variable. If the user
pressed cancel, a value of "false" is returned. In JavaScript, we can detect
this false value by using the exclamation mark (!
). Then by using the
prebuilt window.location
property, we can change the contents of the
document to the specified url accordingly.
As you learn more about JavaScript, you will be able to build more complex JavaScript boxes that will irritate your surfers even more.
Ok, having looked at the three methods (commands), let me introduce you to an alternate way of writing the methods that save you some time.
In all our examples above, we wrote the three methods as follows:
- window.alert()
- window.confirm()
- window.prompt()
Actually, we could ALWAYS simply write the following instead:
- alert()
- confirm()
- prompt()
For example:
<script type="text/javascript"> alert("this is really good on my wrist!") </script>
The three commands we have just gone through all have practical (and annoying sometimes) uses that I'm sure you've seen on the web. Try them out, play around with them, but don't get too close to them!
- Tutorial introduction
- The alert, confirm, and prompt boxes
- A more complex example of interactive dialog boxes