-1

When receiving a notification in facebook the document title will be updated automatically

(1) Facebook

How to do this with javascript?

UPDATE: I want to know how to insert the (N) and remove it when a users clicks a specified div.

Chris
  • 4,255
  • 7
  • 42
  • 83

1 Answers1

6

There is an easy way to update the document title:

document.title = 'My new title';

Here is a code snippet which will update the title when a new notification is available and update it again (remove the number of new notifications) when the user clicks the #foo div.

var title = document.title;
var notifications = 0;
jQuery.post(url, data, function(response) {


    // this regex will test if the document title already has a notification count in it, e.g. (1) My Document
    if (/\([\d]+\)/.test(title)) {
        // we will split the title after the first bracket
        title = title.split(') ');
        // get the first part of the splitted string and save it - this will be the count of the unseen notifications in our document string
        notifications = title[0].substring(1);

        // only proceed when the notification count is difference to our ajax request
        if (notifications == response)
            return;
        // else update the title with the new notification count
        else
            document.title = '(' + sp_response + ') ' + title[1];   
    }   
    // when the current document title does not contain any notification count, just update it
    else {
        document.title = '(' + sp_response + ') ' + title;
    }

});

jQuery('#foo').click(function(event){
    var title = document.title;
    if (/\([\d]+\)/.test(title)) {
        title = title.split(') ');
        document.title = title[1];  
    }
});
Chris
  • 4,255
  • 7
  • 42
  • 83