Fixing alert() Hell: divalert()

It often occurs in creating Javascript programs that you have a need to display something to the screen. The simplest way to accomplish this is through the alert() function like so:

  alert('Hello World!');

This pops up the typical Javascript alert box, you click "OK", and all is well.

But sometimes you need to display a bit more text. Or perhaps you want to display a value inside a loop... Suddenly you're clicking through a seemingly endless stream of alert boxes. And the damn things just won't go away until you click every last one.

To replace this common malady (and others), I've created divalert(). It works just like alert, but better:

  divalert('Hello World!');

What makes this better? Well, for one thing, you don't have to click "OK" anywhere to keep using the page (on the rare occasions where you do need that behavior, by all means use alert()). Another big improvement is that any new alerts are also displayed in a running log.

For a much better idea of divalert()'s capabilities, take a look at this simple example. By all means, take a look at divalert's source.

The Care and Feeding of divalert()

Installation

Installing and using divalert is very simple. If it weren't I wouldn't use it and I wouldn't expect anyone else to either. It is completely contained in a single file. Grab divalert.js here.

After grabbing divalert.js, include it in your page like so:

<script type="text/javascript" src="divalert.js"></script>

That's all there is to installation!

Use

Using divalert is quite simple. Call divalert() with the string of your choice just as you would with alert().

<script type="text/javascript">
  var goodStuff = "ice cream";
  divalert("Good stuff: "+goodStuff);
</script>

If you've been a Javascript developer for a while, you're probably wondering what happens when you call divalert() before the page body is loaded. Excellent question. When this occurs, divalert() does not attempt to append itself to the document body. Instead, it waits invisibly in memory and attaches an event handler to window.onload. Check out the example to see it in action. Notice that when it is called before the body loads, divalert() automatically prints a message, *Page Loaded* when the body has loaded. This in and of itself can be quite helpful for debugging.

One final thing you can do when calling divalert() is to call for a bold alert. Simply call divalert with "true" as your second parameter:

  divalert('Bold Text', true);