This blog will teach us how to create an Auto-Text Typing Effect JavaScript Project.
The GitHub source code of this project is attached below.
First let’s see how this project looks like:
How to create the auto-text typing effect using JavaScript?
We have created an UpdateText function in the Script.js file to create the auto-text typing effect.
HTML PART:
HTML Part is very simple to understand. We created a ‘div’ element that will be displayed on the web browser and our intuition is to insert ‘text’ inside this ‘div’ element using the JavaScript function.
<body>
<div class="container">
//auto-text will get inserted here
</div>
<script src="script.js"></script>
</body>
CSS PART:
Firstly, we have given the height and width of the container that will hold the auto-text data.
body{
display: flex;
justify-content: center;
height: 50vh;
align-items: center;
background-color: rgb(255, 255, 255);
}
JavaScript PART:
This is the main part of this project; we are creating an update function that will update or add the text inside the container at regular intervals.
Intuition of Update() function:
In updateText(), we have an array having texts that we want to show. By using setTimeOut(), we are accessing each index of the array and showing every character of the current index word at one interval. Once the index reaches the end of the array, we have to repeat the array elements from the start hence we are again setting the index to the initial place so that the loop never ends.
const containerEl = document.querySelector(".container")
const careers = ["Developer", "Youtube", "Freelancer", "Investor"];
let index = 0;
let characterIndex=0;
function updateText() {
containerEl.innerHTML = ` <h1>I am ${careers[index].slice(0,characterIndex)}</h1>`;
if(characterIndex===careers[index].length){
index++;
characterIndex=0;
}
if(index>=careers.length){
index=0;
}
characterIndex++;
setTimeout(updateText,200);
}
updateText()
Source Code Link: (Link)
Refer to this link for more coding projects: Projects