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 badges1 Answer
Reset to default 7For 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>