Setting Title Tags Using JavaScript: Inspired by Facebook Chat Notification
HTML <title>
tag is a meta tag mostly used for website information purposes.
When you set a title tag on your page's .html
file
it will show up on the browser tab:
And also shows up on search results:
But you can also change the title tag pragmatically using JavaScript.
All you have to do is to modify the document.title
property.
I love how Facebook cleverly used the title area to notify about the new chat messages.
Here I have put together a basic implementation of the FB chat title effect.
First, you will store the current title tag in a constant value:
const currentTitle = document.title
Next, you will create a setInterval
method to change the title every 1 second:
setInterval(function() {
if(document.title == currentTitle) {
document.title = "Tamal Sent You a Message"
} else {
document.title = currentTitle
}}, 1000)
The setInterval
method is a global method in JavaScript. By default, it takes a callback function and the interval amount (integer). The callback function will run every X time. In this case, it will run every 1000 milliseconds or every 1 seconds.
Inside the callback function, the logic toggles between the titles using an if/else condition.
I hope you learned something new today. If so, show some love 🧡
Subscribe to my newsletter
Read articles from Tamal Chowdhury directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Tamal Chowdhury
Tamal Chowdhury
Learning and Building in public with React, JavaScript, NodeJS, Chrome Extensions, Android, Kotlin. I write, create & teach. Let's connect!