Wednesday, November 11, 2015

HTML Flash Messages

Occasionally, and especially during the debugging phase of a development effort, I like to be able to create a message that appears in the web page on which I'm working, one that disappears after a few seconds. A flash message.

In the past, I've accomplished this in a variety of ways, including timeouts and so on. And some frameworks (Tapestry, e.g.) provide this kind of thing from the server as a built-in mechanism. But I'm just interested in doing this from within javascript.

Anyway, I was recently fooling around with prototypes and extending the javascript String object, and it occurred to me that a String extension to flash a message would be trivial to do, epsecially with JQuery to handle the timing parts. So I wrote this:

String.prototype.flash = function(){
    }, 3500);
Coupled with a
element in the HTML in which to display the message

I am able to write flash messages off typical JS Strings:

("This is COOOOOL...").flash();
Which will show that message inside the DIV, then get rid of it after 3.5 seconds. I could extend it to parameterize the time and even the fade effects. But sometimes simpler is bester.