Question

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();
Was it helpful?

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

OTHER TIPS

Pinouchon's answer works but if I had to add an interval check so it didn't speed up the title changing when one person messaged multiple times in a row. So I had

if(timeoutId)
 {
     clearInterval(interval);
 }

 interval = setInterval(changeTitle, 700);

Basically if the interval had already been set, clear it and then reset it.

Just remember to call clearInterval on focus:

(function() {
  var timer,
      title = $('title'),
      title_text = title.text();
  $(window).blur(function() {
    timer = setInterval(function() {
      title.text(title.text().length == 0 ? title_text : '');
    }, 2000)
  }).focus(function() {
    clearInterval(timer);
    title.text(title_text);
  });
})();

You can try this one. You can call the blink function to start switching between two titles and call stop, when you dont want this anymore.

var title = document.title;
var interval = 0;

function blink(title1, title2, timeout){
    title2 = title2 || title;
    timeout = timeout || 1000;

    document.title = title1;
    interval = setInterval(function(){
        if(document.title == title1){
            document.title = title2;
        }else{
            document.title = title1;
        }
    }, timeout);
}

function stop(){
    clearInterval(interval);
    document.title = title;
}



blink('My blinking title!');
setTimeout(function(){
    stop();
}, 5000)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top