jQuery: Show a Operation Status bar which Disappears after a Couple of Seconds CodeUnit 03 JUN 2011

Operation or Message status bars are useful creatures when you want to indicate to a user that their action (perhaps AJAX driven) either succeeded or failed. Popping one up on the screen, setting its colours accordingly and displaying the message before making it disappear again after a couple of seconds becomes pretty trivial when using jQuery.

So here is one way you could do it.

As part of your CSS, define a success-notice and error-notice class which basically sets the foreground and background colours as you would like them to appear on your page. In my case, I like using:

.error-notice {
    padding-left: 10px;
    padding-right: 10px;
    background-color: #f2baba;
    color: #990000;
    border: 2px dashed #b81616;
    font-weight: normal;
    font-size: 0.95em;
    margin-left: 0px;
    margin-right: 0px;
    margin-top: 10px;
    margin-bottom: 10px;
    cursor: pointer;
}

.success-notice {
    padding-left: 10px;
    padding-right: 10px;
    background-color: #baf2bb;
    color: #049900;
    border: 2px dashed #15a612;
    font-weight: normal;
    font-size: 0.95em;
    margin-left: 0px;
    margin-right: 0px;
    margin-top: 10px;
    margin-bottom: 10px;
    cursor: pointer;
}

Then in your code, pop in a hidden element and give it a nice and unique element ID which you can use when it comes to the jQuery bit. For example, you could put down something like <div id=”ajax-status-message” style=”display: none;”> </div>

And now for the fun bit. At the end of your operational javascript, decide on the appropriate status message which is to be returned and then add following call into your code:

//if the operation failed
$('#ajax-status-message').html(message).removeClass('success-notice').addClass('error-notice').show().delay(5000).fadeOut();
//if the operation succeeded
$('#ajax-status-message').html(message).removeClass('error-notice').addClass('success-notice').show().delay(5000).fadeOut();

What the above does, is basically locate the existing message div, set the contained text to your status message, strip the existing CSS class if already attached and attach the correct CSS class based on whether or not you decided that the operation succeeded or failed. Then unhide it so that the user can see it and after five seconds, cause it to gracefully fade out of view.

Nifty.

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.