Creating Custom JavaScript Alerts

Slayeroffice has a
nice tutorial
on creating custom JavaScript alert boxes. Custom
alert boxes, in and of themselves, are nothing to write home about, but the
slayeroffice tutorial suggests an interesting twist. Rather than calling your own
alert function, like this…

if (foo) {
myCustomAlert("Hey, you can't do that!");
}

… they suggest actually replacing the default window.alert() function with your
own. There’s plenty of code in the tutorial, but here’s the code that actually
performs the magic:

window.alert = function(txt) {
createCustomAlert(txt);
}

What’s the advantage of overriding the default window.alert() function rather
than calling your own? First, it’s way cooler. But second, it allows you to easily
retrofit existing applications with new and improved alert boxes.
For instance, most web applications include a common header, so in order to change
all the alert boxes for an entire application, you can simply drop some new code
in your application’s header, and magically, all those ugly gray default alert
boxes are transformed. Pretty cool stuff.

3 Responses to Creating Custom JavaScript Alerts

  1. stanton says:

    Very cool custom alert. I like it a lot and plan to use it in the future (so much better than the generic, Windows grays). Thanks for posting the info.Mike

  2. Oliver Tse says:

    This is clever. One major difference is that the custom alert is not really modal (the article referred to it as “pseudomodal”).This is because original the alert() function **typically** blocks (Unlike it’s cousins prompt() and confirm(), it does not always block. The behavior is dependent on the browser, but modern browsers such as IE 5.x and Firefox have the alert() function blocking).Blocking is critical if your application is dependent on proceeding after the alert dialog is acknowledged rather than proceeding while the alert dialog is being shown.