Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 630
Benjamin Crouzier Avatar asked Nov 28 '22 17:11

Benjamin Crouzier


2 Answers

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);
});
like image 181
Benjamin Crouzier Avatar answered Dec 01 '22 06:12

Benjamin Crouzier


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.

like image 21
rjg132234 Avatar answered Dec 01 '22 08:12

rjg132234