Tag Archives: jquery plugin

How to display little temporary javascript messages to the user ?

Standard

Hello everyone,

Today, I’ll talk about displaying little notification messages at the bottom of a web page, and how to make them appear and vanish after a few seconds in a customizable way, thanks to JQuery. Let’s say we need to display messages that would stack up against each other, and each would appear and disappear after a specified time. We want to :

–          Style the notifications (error, validation…)
–          Style the whole notification template and put whatever we want in it
–          Notifications should anchor to the bottom of the page, wherever we’re scrolling at.
–          All this within a jquery plugin ?

To ease our task, we’d rather use jquery template.

First, refer the scripts you need at the end of the page to prevent them from slowing html rendering :

  <script src="Scripts/jquery-1.9.1.js"></script>
    <script src="Scripts/jquery-tmpl.js"></script>
    <script src="Scripts/notificationMaker.js"></script> <!--our plugin-->

Then create your page. For the sake of the demo, we add 3 buttons, one for displaying negative messages, one for good messages, the last one for custom templated messages. We add a long text excerpt to check that scrolling doesn’t affect our notification messages anchor.

 <div id="whole">
            <div id="buttons">
                <textarea id="myMessage"></textarea>
                <br />
                <button id="notification-negative">post alert</button>
                <button id="notification-positive">post good message</button>
                <br />

                <button id="templated-notification">post custom message</button>
            </div>
            <div id="content">
                    "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
            1914 translation by H. Rackham

             "... and so on ... (big text to show even when scrolling notification messages stay put"
            </div>
        </div>

Then write the script that will use our notification jquery plugin. I just wrote an example, but you can use it any way you want. First function will use a simple css class for styling good messages. Second function will use a different css class for errors then specify how many milliseconds the message will appear.

<script type="text/javascript">
        $(document).ready(function () {
            $("#notification-positive").click(function () {
                var value = $("#myMessage").val();
                $.postMessage(value,
                    {
                        cssClass: "notification-message",
                    })
                ;
            });
            $("#notification-negative").click(function () {
                var value = $("#myMessage").val();
                $.postMessage(value,
                    {
                        cssClass: "notification-error",
                        time:4000,
                    })
                ;
            });
       });
    </script>

A third function specify a custom template, giving its selector.

$("#templated-notification").click(function () {
                var value = $("#myMessage").val();
                $.postMessage(value,
                    {
                        template: "#my-message-template",
                    });
            });

And here’s the template

 <script id="my-message-template" type="text/html">
        <div class="templated-part">
            <p>{{= Message }}</p>
        </div>
    </script>

Of course you could build the template the way you want, with pictures, other div, span or whatever inside it. Just evaluate the “Message” variable wherever you want to show the text message.

Now let’s show the interesting part, the plugin part  with all comments :

(function ($) {
    var notificationMaker = {
        messageArea: null,
        init: function () { //just once at the beginning to insert the message area once into the DOM
            if (notificationMaker.messageArea)
                return;
            messageArea = document.createElement('div');
            $(messageArea).addClass("notification-area"); //style the notification area in stylesheet if you don't want it that way
            $("body").append(messageArea);
        },
        //method that shows the messages for a specific time and with animations
        showMessage: function (elm, time) {
            $(elm).slideToggle();//or use whatever animation you want
            setTimeout(function () {
                $(elm).slideToggle({
                    complete: function () {
                        messageArea.removeChild(elm); //important, remove the element from DOM so that DOM doesn't grow too much
                    }
                });
            }, time);
        },
        methods: {
            //options : cssClass, custom template, time to display the message
            postMessage: function (message, options) {
                var element = null;
                options = (!options) ? {} : options;
                var time = (options.time) ? options.time : 3000; //sets a default time if none specified
                if (!options.template) { //if no template, that's gonna be a paragraph
                    element = document.createElement('p');
                    if (options.cssClass) //if there's a specified css class
                        $(element).addClass(options.cssClass);
                    $(element).text(message); //sets the text
                }
                else {
                    element = $(options.template).tmpl({ Message: message })[0]; //apply a jquery template,
                    //take the first of the array a jquery template will return an array
                    //we need an object only to remove it from DOM later
                }
                $(element).hide();
                $(messageArea).append(element);
                notificationMaker.showMessage(element, time);
                return this;
            },
        }
    };

    //add the plugin method to jquery methods, beware not to replace any jquery native methods.
    $.postMessage = function(method) {
        var methods = notificationMaker.methods;
        if (typeof method === 'string') {
            if (method !== "")
                return methods.postMessage.apply(this, arguments);
            else return this;
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.notificationMaker');
        }
    };
    notificationMaker.init();

})(jQuery);

That way, it is clipped to the page’s bottom, no matter if you scroll the page, thanks to a custom JQuery plugin.

Here’s the zipped project if you want the whole thing with css :

Client side notifications sample

Enjoy 😉

Advertisements