Posts Tagged ‘javascript’

Flashing Browser Title

Monday, July 20th, 2009

So as part of this chat application I’m writing, I was told that I needed to alert the user that a new message had arrived, even if the window was minimized. So I decided to flash the document title with different text. This seemed pretty straight forward, but I thought I would post what I did, in case someone else needed to solve the same problem. Keep in mind that the originalMsg and changeMsg in my application are set on the server side because they are dynamically generated, but if you don’t have that requirement, you can just enter the static text in the JavaScript directly.

Enjoy!

        // Create the variables
        var timer1 = null;
        var timer2 = null;
        var originalMsg = “”;
        var changeMsg = “”;

        function changeTitle() {
            if (document.title == originalMsg)
                document.title = changeMsg;
            else
                document.title = originalMsg;
        }

        function delayChange() {
            timer2 = setInterval(”changeTitle()”, 2000);
        }

        function startFlashTitle() {

            if (timer1 == null && timer2 == null) {
                timer1 = setInterval(”changeTitle()”, 2000);

                setTimeout(”delayChange()”, 1000);
            }
        }

        function stopFlashTitle() {
            if(timer1 != null) clearInterval(timer1);
            if(timer2 != null) clearInterval(timer2);

            document.title = originalMsg;
            timer1 = null;
            timer2 = null;
        }