• Follow sebaube on Twitter
  • Subscribe to sebaube.com
 
 

Creating a twitter like flash message

Here’s a quick step by step tutorial to create a Twitter style Flash message using css and javascript.

The CSS
I’m using the blueprint css which can be found here

.notification
{
    text-align: center;
    display: none;
    width: 100%;
    position: fixed;
    padding-top: 8px;
    padding-bottom: 8px;
    margin: 0;
    font-weight: bold;
    font-size: 1.2em;
    overflow: visible;
}

Add the following html somewhere before the Body closing tag.

<div id="notification" class="notification">
	<span id="notification-text"></span>
</div>

And the javascript:
As you can probably tell we are using the JQuery library. We wanted the flash message to show up for a decent amount of time after witch it would go away. Luckily JQuery has the fadeIn and fadeOut animation methods. To make it more JQuery like we added a callback function. This callback will be invoked once the Flashmessage has completed it’s fadeOut.

//Provide a variable to hold the callback function
var notifyCallBack;

function showNotification(message, type, callback) {

    notifyCallBack = callback;

    var notification = $("#notification");
    notification.removeClass("success notice error");
    notification.addClass(type);

    //Make sure it's visible even when top of the page not visible
    notification.css("top", $(window).scrollTop());
    notification.css("width", $(document).width());

    $("#notification-text").html(message);

    //show the notification
    notification.slideDown("slow", function() {
        setTimeout(hideNotification,
            4000 // 4 seconds
            )
    });
}

function hideNotification() {
    $("#notification").slideUp("slow", function() {
        if (null != notifyCallBack && (typeof notifyCallBack == "function")) {
            notifyCallBack();
        }
        //reset the callback variable
        notifyCallBack = null
    });
}

Here’s a typical scenario where the showNotification would be usefull

$(form).ajaxSubmit({
		success: function(data) {
			if (true == data.isSuccessful){
				showNotification(data.FlashMessage, "success", function(){
					//do something
				});
			}
			else{
				showNotification(data.ErrorMessage, "error", function(){
					//display errors
				});
			}
		},
		dataType: "json"
	});
TwitterFacebookTechnorati FavoritesYahoo BuzzDiggStumbleUponRedditGoogle ReaderShare

Products

Bad Behavior has blocked 133 access attempts in the last 7 days.