简体   繁体   中英

Best way to make title bounce when a new message is received and tab is inactive?

This is what I have so far, but it's ugly and feels non-best practicey. For example, if multiple messages are received, it starts the changeTitle cycle multiple times.

var hasFocus = true;
$(window).bind("blur", function() { 
    hasFocus = false;
});
$(window).bind("focus", function() {
    hasFocus = true;
    document.title = 'SiteName | Chat'; 
});
var i=0;
function changeTitle() {
    i++;
    if(i%2) {
        document.title = 'New message on SiteName!';
    }
    else {
        document.title = 'SiteName | Chat';
    }
    if(!hasFocus) {
        setTimeout('changeTitle()',1000);
    }
}

// Then I call changeTitle() when a new message is received.

This is what I ended up doing.

function changeTitle() {
    i++;
    if(i%2) {
        document.title = 'New message on mysite!';
    }
    else {
        document.title = 'MySite | Chat';
    }
    if(!hasFocus) {
        titleCurrentlyChanging = true;
        setTimeout('changeTitle()',1000);
    }
    else {
        titleCurrentlyChanging = false;
        i=0;
        document.title = 'MySite | Chat';
    }
}

Inside the addMessage() function, which is called when a new message is received:

if(!hasFocus && !titleCurrentlyChanging) {
    changeTitle();
}

Inside the global namespace:

var i = 0;
var titleCurrentlyChanging = false;

var hasFocus = true;
$(window).bind("blur", function() { 
    hasFocus = false;
});
$(window).bind("focus", function() {
    hasFocus = true;
    document.title = 'MySite | Chat'; 
});

Off the top of my head I can think of three:

  1. The Better gReader add-on for Firefox actually changes the favicon of the tab to show unread posts. Have a look at this question: Changing website favicon dynamically
  2. The new Meta SO chat adds a (*) to the front of the title. This is somewhat reminiscent of IDEs which stick an asterisks to help inform user of unsaved files
  3. If the messages are important and time sensitive (eg. chat) you might want to play a small sound to alert the user of new messages

These method would, of course, taking some getting used to, although it would certainly be less intrusive than constantly changing title.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM