最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change Page Title After a Certain Time - Stack Overflow

programmeradmin2浏览0评论

I am trying to dynamically change the title of a page after 2 seconds (2000 ms).

Here is the code I have tried:

<!DOCTYPE HTML>
<html>
<head>
<title>Before</title>
</head>
<body onload="updateTitle">
<script>
var title = document.getElementsByTagName('title');
function updateTitle() {
//Here is some kind of delay (of 2 seconds). I have tried setTimeout(), setInterval() and delay()
title.innerHTML = "After";
</script>
Dummy Content for Body
</body>
</html>

How might this be modified so that after 2 seconds, the page title changes?

I am trying to dynamically change the title of a page after 2 seconds (2000 ms).

Here is the code I have tried:

<!DOCTYPE HTML>
<html>
<head>
<title>Before</title>
</head>
<body onload="updateTitle">
<script>
var title = document.getElementsByTagName('title');
function updateTitle() {
//Here is some kind of delay (of 2 seconds). I have tried setTimeout(), setInterval() and delay()
title.innerHTML = "After";
</script>
Dummy Content for Body
</body>
</html>

How might this be modified so that after 2 seconds, the page title changes?

Share Improve this question edited May 18, 2013 at 16:20 Brad 164k56 gold badges377 silver badges554 bronze badges asked May 18, 2013 at 16:18 Z. EdwardsZ. Edwards 676 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

For changing the title, you should rather be using window.title

window.title = 'After';

In case, you absolutely must use document.getElementsByTagName, note that it returns an array of elements, the first of which you need to make use of. i.e.

document.getElementsByTagName('title')[0].innerHTML = 'After';

Of course, if the page does not have a <title> element, the above will result in an error. The first one (window.alert) will work in either case.


Delay

For introducing the delay, you can use setTimeout (as you've already done)

<script>
function updateTitle() {
    setTimeout(function() {
        window.title = 'After';
    }, 2000);
}
</script>

Full page working code:

Notice that the block containing updateTitle() has been moved to the . The issue was that the function updateTitle() was not yet defined when the browser tried to bind it to onload (while parsing the page) - as it was defined afterwards inside the body.

<!DOCTYPE html>
<html>
<head>
<title>Before</title>
<script>
function updateTitle() {
    setTimeout(function() {
        document.getElementsByTagName('title')[0].innerHTML = 'After';
    }, 2000);
}
</script>
</head>
<body onload="updateTitle()">
Dummy Content for Body
</body>
</html>
发布评论

评论列表(0)

  1. 暂无评论