Skip to content

Instantly share code, notes, and snippets.

@stellasphere
Created November 13, 2023 21:57
Show Gist options
  • Save stellasphere/6a089ed3148875cc18cdf6f9828598d9 to your computer and use it in GitHub Desktop.
Save stellasphere/6a089ed3148875cc18cdf6f9828598d9 to your computer and use it in GitHub Desktop.
A rotating slot-like text animation.
async function rotateText(target, texts, options={}) {
// target: the container of the text
// texts: an array with the text you want it to rotate between
// options: see below
var defaultOptions = {
rotateTime: 3000,
transitionTime: 500,
startText: 0,
appearFirst: true,
debug: false
}
Object.assign(options,defaultOptions)
var debug = options.debug
console.log("options:",options)
var targetElement = document.querySelector(target)
targetElement.innerHTML = ""
console.log("container element:",targetElement)
for(t in texts) {
let text = texts[t]
let textElement = document.createElement("p")
textElement.classList.add("rotate-text")
textElement.id = `rotate-text${t}`
textElement.innerText = text
textElement.style.transition = `${options.transitionTime}ms`
if(options.startText == t) textElement.style.transform = "translate(0, 0)"
targetElement.appendChild(textElement)
}
if(options.appearFirst) await sleep(options.rotateTime)
var currentText = options.startText
var interval = setInterval(async () => {
let nextText = currentText+1
if(nextText >= texts.length) nextText = 0
if(debug) console.log("rotating:", nextText)
let currentTextElement = document.querySelector(`#rotate-text${currentText}`)
let nextTextElement = document.querySelector(`#rotate-text${nextText}`)
// TRANSITIONS
// Ensure Previous States
currentTextElement.style.display = "block"
nextTextElement.style.display = "block"
currentTextElement.style.transform = "translate(0, 0%)"
nextTextElement.style.transform = "translate(0, -100%)"
await sleep(options.transitionTime)
// Next State
currentTextElement.style.transform = "translate(0, 100%)"
nextTextElement.style.transform = "translate(0, 0%)"
await sleep(options.transitionTime)
// End State
currentTextElement.style.display = "none"
currentTextElement.style.transform = "translate(0, -100%)"
currentText = nextText
},options.rotateTime-options.transitionTime)
return interval
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment