A more complex example of interactive dialog boxes
Using these three basic methods (
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:
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
this false value by using the exclamation mark (
!). Then by using the
window.location property, we can change the contents of the
document to the specified url accordingly.
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:
Actually, we could ALWAYS simply write the following instead:
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!