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

Benjamin Crouzier picture Benjamin Crouzier · Oct 1, 2011 · Viewed 11.6k times · Source

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();

Answer

Benjamin Crouzier picture Benjamin Crouzier · Oct 1, 2011

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);
});