开发者

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

开发者 https://www.devze.com 2023-04-10 11:25 出处:网络
I have a javascript chat. When a user receives a message, I want the title to blink until it becomes active. (like Gmail Talk)

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: bl开发者_如何学Goa 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();


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


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消