Skip to content

Instantly share code, notes, and snippets.

@giuseppe998e
Last active June 6, 2023 08:58
Show Gist options
  • Save giuseppe998e/d4f7f8a0ac6a9f2234a235e5181f977a to your computer and use it in GitHub Desktop.
Save giuseppe998e/d4f7f8a0ac6a9f2234a235e5181f977a to your computer and use it in GitHub Desktop.
Javascript code that shuffles the text of an HTML element
!function () {
const shuffleVelocityMs = 50;
const shuffleElement = (element) => {
const elemText = element.getAttribute("data-text");
const elemementChars = Array.from(elemText);
const shuffleChars = (chars) => {
for (let idx = chars.length; --idx; ) {
const randomIdx = parseInt(Math.random() * idx);
const cachedChar = chars[idx];
chars[idx] = chars[randomIdx];
chars[randomIdx] = cachedChar;
}
return chars;
};
const shuffleText = (chars_no, char_idx) => {
if (char_idx == chars_no) {
element.textContent = elemText;
return;
}
setTimeout(() => {
const randomChars = shuffleChars(elemementChars.slice(char_idx));
element.textContent = elemementChars
.slice(0, char_idx)
.concat(randomChars)
.join("");
shuffleText(chars_no, ++char_idx);
}, shuffleVelocityMs);
};
shuffleText(elemementChars.length, 0);
};
setTimeout(() => {
const element = document.querySelector(".shuffle");
element.setAttribute("data-text", element.textContent);
shuffleElement(element);
}, 100);
}();
!function(){const t=t=>{const e=t.getAttribute("data-text"),n=Array.from(e),o=(c,r)=>{r!=c?setTimeout((()=>{const e=(t=>{for(let e=t.length;--e;){const n=parseInt(Math.random()*e),o=t[e];t[e]=t[n],t[n]=o}return t})(n.slice(r));t.textContent=n.slice(0,r).concat(e).join(""),o(c,++r)}),50):t.textContent=e};o(n.length,0)};setTimeout((()=>{const e=document.querySelector(".shuffle");e.setAttribute("data-text",e.textContent),t(e)}),100)}();
@giuseppe998e
Copy link
Author

Example at giuseppe.eletto.me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment