Search code examples
javascriptjqueryhtmlnotificationsblink

How to make a title blink until it becomes active with jQuery?


I have a javascript chat. When a user receives a message, I want the title to blink until it becomes active. (like Gmail Talk)

For example:

  • You are in an other tab. Title is My website
  • Someone talks to you. Title blinks betwen My website and User says: bla bla
  • So you click the tab, and now the title is My website

How can I achieve that using jQuery ?


What i tried so far: (blinking never stop playing)

var isOldTitle = true;
var oldTitle = "oldTitle";
var newTitle = "newTitle";
function changeTitle() {
     document.title = isOldTitle ? oldTitle : newTitle;
     isOldTitle = !isOldTitle;
     setTimeout(changeTitle, 700);
}
changeTitle();

Solution

  • Full solution:

    var isOldTitle = true;
    var oldTitle = "oldTitle";
    var newTitle = "newTitle";
    var interval = null;
    function changeTitle() {
        document.title = isOldTitle ? oldTitle : newTitle;
        isOldTitle = !isOldTitle;
    }
    interval = setInterval(changeTitle, 700);
    
    $(window).focus(function () {
        clearInterval(interval);
        $("title").text(oldTitle);
    });