November 17, 2010

jQueryUI plugin: Highlight and Error Alerts

So I've been working with jQuery for a while and have been digging into jQueryUI lately as well. I found rather quickly, however, that there is no built-in method for creating a Highlight or Error alert like those shown in the jQueryUI themeroller. So, I've created a very simple plugin to use specifically for that purpose:

(function($){
     $.fn.writeError = function(message){
        return this.each(function(){
           var $this = $(this);

           var errorHtml = "<div class=\"ui-widget\">";
           errorHtml+= "<div class=\"ui-state-error ui-corner-all\" style=\"padding: 0 .7em;\">";
           errorHtml+= "<p>";
           errorHtml+= "<span class=\"ui-icon ui-icon-alert\" style=\"float:left; margin-right: .3em;\"></span>";
           errorHtml+= message;
           errorHtml+= "</p>";
           errorHtml+= "</div>";
           errorHtml+= "</div>";

           $this.html(errorHtml);
        });
     }
})(jQuery);

(function($){
     $.fn.writeAlert = function(message){
        return this.each(function(){
           var $this = $(this);

           var alertHtml = "<div class=\"ui-widget\">";
           alertHtml+= "<div class=\"ui-state-highlight ui-corner-all\" style=\"padding: 0 .7em;\">";
           alertHtml+= "<p>";
           alertHtml+= "<span class=\"ui-icon ui-icon-info\" style=\"float:left; margin-right: .3em;\"></span>";
           alertHtml+= message;
           alertHtml+= "</p>";
           alertHtml+= "</div>";
           alertHtml+= "</div>";

           $this.html(alertHtml);
        });
     }
})(jQuery);


Note: I've put each function in its own closure to make it easier to integrate one or the other into your code.

The usage of the writeAlert function would be something like the following:

$("#myDiv").writeAlert("Form submitted successfully.");

And, of course, chainability is maintained, so you can animate your alert/error messages with something like the following:

$("#myDiv").writeAlert("Form submitted successfully.").fadeIn("slow").delay(3000).fadeOut("slow");

Happy coding!
Post a Comment