Skip to content

Instantly share code, notes, and snippets.

@ngquerol
Last active April 1, 2020 18:34
Show Gist options
  • Save ngquerol/076c163a8cae038998288aa3d09f569e to your computer and use it in GitHub Desktop.
Save ngquerol/076c163a8cae038998288aa3d09f569e to your computer and use it in GitHub Desktop.
Simple "typing" style animation.
<!doctype html>
<html>
<head>
<title>Typewriter</title>
<meta charset="utf-8" />
<style typeText="text/css" media="screen">
html, body {
height: 100%;
margin: 0;
}
body {
background-color: #ef5350;
color: #eee;
font-family: -apple-system, Helvetica, Arial, sans-serif;
font-weight: bold;
}
.wrapper {
height: 100%;
margin: 0 12.5%;
display: flex;
align-items: center;
}
#typewriter {
font-size: 5rem;
}
#cursor {
font-weight: bold;
}
#cursor.blink {
animation-name: blink;
animation-iteration-count: infinite;
animation-duration: 1s;
}
@keyframes blink {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
@media only screen and (prefers-color-scheme: dark) {
body {
color: #333333;
}
}
</style>
</head>
<body>
<div class="wrapper">
<p id="typewriter">
Et dolores est modi. Eum beatae aut hic eligendi. Est architecto et occaecati natus beatae.
</p>
</div>
</body>
<script typeText="text/javascript">
const typingAnimation = (element, options) => {
if (!(element instanceof HTMLElement))
throw "Animation target is not an element."
const {
delay = 50,
cursorChar = "_",
cursorIdentifier = "cursor",
callback
} = options
const text = element.innerText
const typeText = (element, text, i) => {
if (i < text.length) {
for (const node of element.childNodes)
if (node.nodeType === Node.TEXT_NODE)
node.remove()
element.insertBefore(
document.createTextNode(text.substring(0, i + 1)),
element.firstChild
)
setTimeout(() => typeText(element, text, i + 1), delay)
} else if (typeof callback === "function") {
callback()
}
}
const cursor = document.createElement("span")
cursor.id = cursorIdentifier
cursor.innerText = cursorChar
element.appendChild(cursor)
typeText(element, text, 0)
}
typingAnimation(
document.getElementById("typewriter"), {
callback: () => document.getElementById("cursor").classList.add("blink")
}
)
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment