Skip to content

Instantly share code, notes, and snippets.

@alexnoz
Last active May 1, 2020 18:12
Show Gist options
  • Save alexnoz/26ac460d3da2232e38808143044bfbe5 to your computer and use it in GitHub Desktop.
Save alexnoz/26ac460d3da2232e38808143044bfbe5 to your computer and use it in GitHub Desktop.
Simple type simulation
<style>
.text {
position: relative;
}
.text.type-finished::before {
animation: .5s steps(2, jump-none) 0s infinite alternate pulse;
}
.text::before {
content: '';
height: 1em;
width: 2px;
position: absolute;
right: -2px;
bottom: 0;
background-color: black;
}
@keyframes pulse {
from { opacity: 1; }
to { opacity: 0; }
}
</style>
<span class="text"></span>
<script>
const random = (min, max) => ~~(Math.random() * (max - min) + min)
const wait = time => new Promise(r => setTimeout(r, time))
async function type(text, target, delay = random(50, 200)) {
for (const ch of text) {
await wait(delay + random(-50, 50))
requestAnimationFrame(() => target.insertAdjacentText('beforeend', ch))
}
}
const $span = document.querySelector('.text')
type('Hi there!', $span).then(() => $span.classList.add('type-finished'))
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment