Skip to content

Instantly share code, notes, and snippets.

@canalun
Last active October 20, 2024 07:14
Show Gist options
  • Save canalun/966f4600017f44afe3c4da1333193d3f to your computer and use it in GitHub Desktop.
Save canalun/966f4600017f44afe3c4da1333193d3f to your computer and use it in GitHub Desktop.
text oscillator
const cname = "movearound-text-domdom-enjoy"
addClassToTextsAndImagesRecursively(document.body)
const targets = Array.from(document.getElementsByClassName(cname))
setInterval(() => oscillateElements(targets), 100)
function addClassToTextsAndImagesRecursively(root) {
if (root.tagName === "HEAD" || root.tagName === "SCRIPT" || root.tagName === "STYLE") return
const extendedChildNode = (node) => node.firstChild || node.shadowRoot || node.contentDocument
let child = extendedChildNode(root)
while (child) {
if (isEffectiveTextNode(child)) {
const charSpans = Array.from(child.nodeValue).map((c)=>{
const s = document.createElement('span')
s.classList.add(cname)
s.textContent = c
return s
})
child.replaceWith(...charSpans)
child = charSpans[charSpans.length - 1].nextSibling
} else if (child.tagName === 'IMG') {
child.classList.add(cname)
child = child.nextSibling
} else {
addClassToTextsAndImagesRecursively(child)
child = child.nextSibling
}
}
}
function oscillateElements(elements) {
elements.forEach((e) => {
Object.assign(e.style, {
display: 'inline-block',
transform: `translate(${Math.random() * 10}px, ${Math.random() * 10}px)`
})
})
}
function isEffectiveTextNode(node) {
return node.nodeType === 3 && node.nodeValue.replace(/\u200b/g, '').trim().replace(/(\s|\n|\t)+/g, '') !== ""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment