IT & Programming

Flashing title bar message with JavaScript

A JavaScript function to show flash message in page title bar like facebook style. You can pass text string as first parameter and integer value as second parameter. Integer is the number of time before it should stop.

Function

(function () {

    var original = document.title;
    var timeout;

    window.flashTitle = function (newMsg, howManyTimes) {
		
        function step() {
			
            document.title = (document.title == original) ? newMsg : original;

            if (--howManyTimes > 0) {
                timeout = setTimeout(step, 1000);
            }            
        }        

        howManyTimes = parseInt(howManyTimes);

        if (isNaN(howManyTimes)) {
            howManyTimes = 5;
        }        

        cancelFlashTitle(timeout);
        step();
    };

    window.cancelFlashTitle = function () {
        clearTimeout(timeout);
        document.title = original;
    };

}());

Calling The Function

flashTitle('2 Unread messages', 10);

Output

Page title should flash 10 times before it finally stop.

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *