Confirmation windows

This program shows how to create confirm windows.

Programming Issues

This example is identical to our image switching with onclick example, except that a confirm window is created before changing the image. If the user selects OK from the confirm window, the image is switched; if the user selects cancel, it is not.

Confirm windows are created in a very similar way to alert windows: confirm("Are you sure you want to change the images to Mars?"). The confirm method returns true if the user selects OK, and false if the user selects cancel.

Note that we use JavaScript's && boolean operator in the script. This is a "logical AND" operator, and for the entire expression to evalute to true, the expressions on both sides of the && operator must also evaluate to true. Thus, the expression if ( newsrc == "mars.jpg" && confirm("Are you sure you want to change the image to Mars?") ) only evalutes to true (and therefore only changes the image to "mars.jpg" if newsrc contains "mars.jpg" (which means that the Earth image is currently showing) and the user selects OK from the confirm window. Note also that we do not have to separately create the confirm window and then check its return value (such as var n = confirm("Are you sure you want to change the image to Mars?"); if ( newsrc = "mars.jpg" && n == true )); we can embed the code to create the window within the conditional expression, as we have done above. This enables us to write more compact and easy-to-understand code.

Note: for simplicity, this example does not use image pre-caching.

Demonstration

Earth

Source and Downloads