In this tutorial, I will show you how to create an animated title like the one I have for my website.
document.title
is the javascript attribute that represents the page's title as seen in the tab bar.
There are some ways to create a scrolling title with only a few lines of code, but in this tutorial, we are going to use a method that allows you to hand-animate whatever you want.
The following code will live inside a script
tag in the head
of the document.
The first step is to create a variable called 'frame' inside the script
tag. This will keep track of what frame the animation should be on. The next step is to create a variable that will represent the title: let title = 'myTitle'
. Set this to whatever the title should be when the javascript is not loaded (when the user has been out of the page for too long). Now we must use the builtin function setInterval(function, time (ms));
. The first parameter is the function to be run each time, and the second is the amount of milliseconds between each time that code is run. To make our code simpler here, we will call an anonymous function using the arrow operator (() => {}
). The parenthesis can be kept empty here, although sometimes they can contain a parameter. Oh yeah, and an anonymous function is a function that is declared without a name, and can't be referenced after it is created, and runs as soon as it is created. They are often used to allow code to be used as a parameter in another function. Anyways, all of our code from here on will run inside this function. The first step is to make sure that the frame
variable will not become greater than the number of frames that we have for our animation. We can do this by saying: if (frame > 9) frame = 0;
, where 9 can be whatever number we want. Now we need a switch () {}
statement that will assign a certain value to the title
variable based on our frame
variable. If you don't know what this is, just google it. Our switch statement will follow this basic structure:
switch (frame) {
case 0:
title = 'whatever'
break;
at the end of each cycle, we will increment frame
(frame++
), then assign document.title
to title
. Set the second parameter of setInterval()
to whatever time in milliseconds you want, ex.setInterval(allourcode, 100)
. Your animated title should now work!