开发者

Append title tag in html

How can I append the title tag? Consider the example of messages page, its title is :

Messages

Now on the middle of the page I check the amount of unread messages开发者_StackOverflow, suppose it is '4' then what I want is that the title of my page should become:

Messages (4)

Should I rewrite the tag or is there another way to append it.


To do with PHP, just echo it within your title element.

If you are wanting to do it with JavaScript, you can do this...

document.title = 'Messages (4) ' + document.title;

However, if you want to change it, it may better off caching the original title to make it easier to update.

var originalTitle = document.title;
var prependToTitle = function(prefix) {
   document.title = prefix + originalTitle;
};

If you simply want to change the title, just set the document.title property.

Update

I want to achieve similar thing like in facebook. Even when the homepage is not fully loaded the title appears but as the notifications are loaded the title also appends

If they appear at the front, they are being prepended, not appended. The JavaScript function above will suit your requirements.


If you're using PHP to check the number of unread messages, you should do the check at the beginning of the page and modify it when you're writing the title tag. This is your only option; PHP cannot update the page after it has been sent to the user.

If you're using Javascript, you can modify the title tag through the DOM as with any other element.


Javascript appears to be your best bet. You can easily update the page title this way:

document.title = "Messages (" + varWithNumberOfMessages + ")";


Do it with JS - for example with jQuery:

var count = 4;
var title = $('title').text();

var updateTitle = function() {
    var newTitle = title;
    if ( count > 0 ) {
        newTitle += ' (' + count + ')';
    }
    $('title').text(newTitle);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜