Thursday, June 26, 2014

How to make Alerts fade in and fade out with Bootstrap 3.0

I wanted to make the alerts work a little nicer by using fade in and fade out. I know there are classes in the CSS to handle the fade in, but they don't work in all browsers. So I wanted to implement some Javascript to make it work

Create a div for your alerts

<div id="alerts">

</div>

We need to create unique Ids, I have used this function to do so

   function createUUID() {
        // http://www.ietf.org/rfc/rfc4122.txt
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
    }

Make a function to show the alert, by adding it dynamically

    function addAlert(message) {
        var id = createUUID();
        var JQueryId = "#" + id;

        $('#alerts').append(
            '');

        $(JQueryId).fadeIn(5000);
        window.setTimeout(function () {

            // closing the popup
            $(JQueryId).fadeTo(300, 0.5).slideUp(2000, function () {
                $(JQueryId).alert('close');
            });


        }, 10000);
    }

Notice that when adding the alert, it is hidden. The JQuery fadeIn API will create the fade effect when the alert is showing. Using setTimeout, we start fading out, and then closing the alert. You can play with the numbers to have the effect you want, but this seems to work nice and make alerts popup nice, and close on their own

Testing the Alerts

    $(document).ready(function () {

        addAlert("test");

        window.setTimeout(function () {
            addAlert("test1");
        }, 1000);

        window.setTimeout(function () {
            addAlert("test2");
        }, 10000);

        window.setTimeout(function () {
            addAlert("test3");
        }, 20000);

        window.setTimeout(function () {
            addAlert("test4");
        }, 20000);


        
    });

The code

You can see the code and the full effect here http://www.bootply.com/Sfn68ySAnB

1 comment:

Unknown said...

Smiling always with a never fading serenity of countenance, and flourishing in an immortal youth. See the link below for more info.


#fading
www.ufgop.org