DotNetCurry Logo

Add Notifications in your Website using jQuery

Posted by: Suprotim Agarwal , on 3/8/2015, in Category jQuery and ASP.NET
Views: 11757
Abstract: This article shows how to use jQuery to build a notification in your Website. You will also learn how to give your visitors the option to permanently close the notification using cookies.

Have you ever seen those notifications on websites that appear at the bottom of the page when you start scrolling down, and disappear when you scroll up? In this article, let’s build one for ourselves. We will also see how to give an option to our visitors to permanently close the notification, in case they find it annoying.

Create a new file called ‘NotificationsUsingPanels.html’. In terms of HTML, all we need is a simple container to hold our notification message, and a span tag that contains the close button:

<div id="note">
    <h3>Your Message Comes Here</h3>
    <span class="close">
       
    </span>
</div>

This Div needs to be positioned in the bottom corner of the page to achieve the effect we’re aiming for. We also need the close button at the top-right corner of the Div.

Here’s how we can style it to achieve the effect. This css has been saved in css/notificationpanel.css

#note{
    display:none;
    position:fixed;
    bottom:0;
    right:3px;
    min-height: 50px;
    height:100px;
    width:500px;
    background: #4679bd;     
    padding: 20px 60px;      
    font: 24px Georgia, serif;     
    color: #fff;     
    border-radius: 9px;
}

.close {
    background: transparent url('../images/close-sign.png') 0 0 no-repeat;
    position: absolute;
    top: 5px;
    right: 5px;
    width:40px;
    height:48px;
    display:block;
}

We start by setting position:fixed to keep our div at the bottom of the page. We have also set visibility of the div to none, as our requirement says that the div should be visible only when the user scrolls down the page. In order to render the close button, we have explicitly set a width and height for it and have set display:block.

This is what we have so far:

s3-notification-panel

To show and hide the notification message when the user scrolls, we will make use of the jQuery .scroll() event which fires whenever the element's scroll position changes, regardless of the cause. In our case, we will apply it to the browser window.

$(window).scroll(function () {
...
});

This is a shortcut for $(window).on( "scroll", function()). Here’s the entire code:

$(function () {
    var $window = $(window),
        $body = $('body'),
        $note = $("#note");

    $window.scroll(function () {
        if ($window.scrollTop() > $body.height() / 2) {
            $note.fadeIn();
        }
        else {
            $note.fadeOut();
        }
    });
});

scrollTop() gets the current vertical position of the scroll bar and we compare it with the height of the scroll to see if we are halfway there. If yes, we show the notification using fadeIn(). When the user scrolls up, the same logic is used to determine if we are about halfway up, and hide the notification using fadeOut().

In order to close the notification, use the following code:

$('.close').on('click', function () {
    $note.fadeOut("slow");
    $window.off('scroll');
});

On the click event of the span, we use fadeOut() to hide the notification panel and remove the scroll event listener from the window object using off().

View the page in the browser and you will be able to show and hide the notification as you scroll.

See a Live Demo

Using Cookies to hide the notification permanently

Some of you by now might have noticed that this solution is not complete. When you hit that close button, the notification is hidden only until the user decides to reload the page again.

In order to hide the notification permanently, we will need to use a Cookie. Cookies are needed because HTTP is stateless. This means that HTTP has no way to keep track of a user’s preference on every page reload. This is where a Cookie is useful so that it remembers and saves the user’s preference. Let’s modify our code to use cookies:

Create a new file called ‘NotificationsUsingCookies.html’. Use the same markup as we used earlier.

Use the following code:

var $window = $(window),
    $body = $('body'),
    $note = $("#note"),
    notifyCookie = document.cookie;

$window.scroll(function () {
    if (($window.scrollTop() > $body.height() / 2) &&
            (notifyCookie.search('hideNote') === -1))
    {
        $note.fadeIn();
    }
    else 
    {
        $note.fadeOut();
    }
});


$('.close').on('click', function () {
    $note.fadeOut("slow");
    $window.off('scroll');
    document.cookie = 'hideNote=true; expires=' +
                        (new Date(Date.now() + (10000 * 1)).toUTCString());
});

The code more or less is the same, except that we are setting a cookie to save the user’s preference and reading it while displaying the notification.

For demo purposes, the cookie is set for 10 seconds. However you can always increase the duration to an hour, a day or even a year.

This was a very basic example of using cookies. If you are looking for a complete example of reading/writing cookies with full unicode support, check the Mozilla documentation. Also note that this example will not work if the user decides to delete the cookie or if the browser does not support cookies.

See a Live Demo

Using a Cookie plugin

Ever since the pre HTML5 era, I have always found the behaviour of document.cookie to be strange. For eg: when you assign to it, it adds/updates a cookie instead of replacing it. Overall I feel it could have been designed better, than what we have now. I kind of tend to rely on a nice cookie plugin, rather than using cookies directly in my code.

The jquery-cookie plugin by Klaus Hartl (https://github.com/carhartl/jquery-cookie/tree/v1.4.1) is a nice lightweight jQuery plugin for reading, writing and deleting cookies. It’s maintained regularly, contains a hosts of features, handles browser quirks and is easy to use.

Create a new file called ‘NotificationsUsingCookiesPlugin.html’. We will use the same markup as we used earlier.

Add the following reference to the page:

<script src="../scripts/jquery.cookie.js"></script>

Let’s modify our sample to use the jQuery cookie plugin instead. The code mostly remains the same except for some changes highlighted here:

var $window = $(window),
    $body = $('body'),
    $note = $("#note");   

$window.scroll(function () {
    if (($window.scrollTop() > $body.height() / 2) &&
                (typeof $.cookie('hideNote') === "undefined"))
    {
        $note.fadeIn();
    }
    else 
    {
        $note.fadeOut();
    }
});


$('.close').on('click', function () {
    $note.fadeOut("slow");
    $window.off('scroll');
    var date = new Date(Date.now() + (30000));
    $.cookie('hideNote', 1, { expires: date });
});

To make it a session cookie, omit the expires option. This way the cookie gets deleted when the browser exits.

If your browser supports HTML5, you can avoid cookies and instead use HTML5 local storage to save user preferences. Unfortunately covering an HTML5 specific example is beyond the scope of this articles but you can always read http://www.dotnetcurry.com/showarticle.aspx?ID=1001 to learn more about how to use HTML5 storage.

For demo purposes, the cookie is set for 30 seconds. However you can increase the duration to an hour, a day or even a year.

See a Live Demo

If you liked this article, take a look at my new book The Absolutely Awesome jQuery Cookbook which contains scores of practical jQuery/jQueryUI recipes you can use in your projects right away.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!