Skip to content

Instantly share code, notes, and snippets.

@karolk
Created April 25, 2020 21:27
Show Gist options
  • Save karolk/d8e6ecf8c9057ac4ef97905d0ce24696 to your computer and use it in GitHub Desktop.
Save karolk/d8e6ecf8c9057ac4ef97905d0ce24696 to your computer and use it in GitHub Desktop.
vanilla js implementation of letters
// @ts-check
const createRandomInteger = (limit) => Math.floor(Math.random() * limit)
const createRandomLetter = () => String.fromCharCode(97 + createRandomInteger(26));
const positionLetter = (element) => {
element.style.width = '1vw'
element.style.height = '1vw'
element.style.lineHeight = '1vw'
element.style.fontSize = '3vh'
element.style.position = 'absolute'
element.style.left = createRandomInteger(95) + 'vw'
element.style.top = createRandomInteger(50) + 'vh'
}
const styleLetter = (element) => {
element.style.backgroundColor = 'rgba(155, 255, 155, 0.8)'
element.style.color = 'black'
element.style.padding = '1em'
element.style.borderRadius = '50%'
element.style.fontFamily = 'sans-serif'
element.style.textAlign = 'center'
element.style.transition = 'top 5s linear, background-color 5s linear'
}
const animateLetter = (element) => {
requestAnimationFrame(() => {
element.style.top = '100vh'
element.style.backgroundColor = 'red'
})
}
const drawLetter = (letter) => {
const span = document.createElement('span')
styleLetter(span)
positionLetter(span)
animateLetter(span)
span.textContent = letter
span.classList.add('letter-' + letter)
document.body.append(span)
}
const findLetter = (letter) => document.querySelector(".letter-" + letter)
const findAndRemoveLetter = (letter) => {
const letterSpan = findLetter(letter)
if (letterSpan) {
letterSpan.classList.remove(".letter-" + letter)
letterSpan.style.color = 'white'
setTimeout(() => {
letterSpan.remove()
}, 500)
}
}
const removeLettersWhenTyping = () => {
document.addEventListener("keypress", (event) => {
findAndRemoveLetter(String.fromCharCode(event.keyCode))
})
}
const createNewLetters = (interval = 1000) => {
setInterval(() => drawLetter(createRandomLetter()), interval)
}
const start = () => {
createNewLetters()
removeLettersWhenTyping()
}
start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment