In this post I will show how to dynamically change document's title using JavaScript and jQuery. Browsing the web (and StackOverflow) I saw a lot of posts that say you can't do it using jQuery. Actually, there is a jQuery syntax that is basically a wrapper for javascript code (see below).
Note: just to clarify, by document title we mean the text that is displayed in the browser window or a tab.
The best way to change the document title is to use native javascript api document.title
.
document.title = "New text set by JavasSript";
The equivalent jQuery code of js code above.
$(document).prop('title', 'New text set by jQuery');
Example
Let's say we need to change the tab title text when a user clicks on a button. Here is a jQuery code to do just that:
<html>
<head>
<title>Initial page title</title>
<script src="path-to/jquery.js"></script>
<script>
$(document).ready(function(){
$('#clickme').click(function(){
document.title = $(this).val();
// jQuery syntax alternative
// $("title").text( $(this).val() );
});
});
</script>
</head>
<body>
<input type="button" id="clickme" name="clickme" value="Click me!" />
</body>
</html>
To conclude, you are better off using document.title
, because it is cross-browser and has performs better.
Alternative jQuery syntax has been tested in all major browsers.