JSFiddle - React, Tailwind, and code Playground
HTML
<script src="<link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:300" rel="stylesheet"> "></script>
<span id="content"></span>
<span id="cursor">|</span>
CSS
body {
background-color: #220023;
color: #BEBEBE;
font-size: 4em;
font-family: 'Source Code Pro', monospace;
}
#container {
position: relative;
top: 45%;
}
#cursor {
-webkit-animation: 1s blink step-end infinite;
-moz-animation: 1s blink step-end infinite;
animation: 1s blink step-end infinite;
}
@keyframes blink {
from,
to {
opacity: 0;
}
50% {
opacity: 1;
}
}
@-moz-keyframes blink {
from,
to {
opacity: 0;
}
50% {
opacity: 1;
}
}
@-webkit-keyframes "blink" {
from,
to {
opacity: 0;
}
50% {
opacity: 1;
}
}
JavaScript
var span = document.getElementById("content");
var strings = ["hello world", "how r u??"];
var index = 0; //access string in the strings array
var chIndex = -1; //get individual char pos for substring generation
var type = true;
var typingFunction = function() {
if (index === strings.length) {
index = 0;
}
if (type) {
typeIt();
} else {
deleteIt();
}
}
var x = setInterval(typingFunction.bind(typingFunction), 200);
function typeIt() {
if (chIndex == -1) {
chIndex += 1;
clearAndRestartInterval(1000);
return;
}
if (chIndex <= strings[index].length) {
span.innerHTML = strings[index].substring(0, chIndex++);
} else {
clearAndRestartInterval(1000);
type = false;
return;
}
}
function clearAndRestartInterval(timeOfRestart) {
clearInterval(x);
setTimeout(function() {
x = setInterval(typingFunction.bind(typingFunction), 200);
}, timeOfRestart);
}
function deleteIt() {
if (chIndex === -1) {
index++;
type = true;
} else {
span.innerHTML = strings[index].substring(0, chIndex--);
}
}