Skip to content

Instantly share code, notes, and snippets.

@aczw
Last active September 26, 2024 05:31
Show Gist options
  • Select an option

  • Save aczw/cd1d5dcd380267e51ed23b89fc427c6e to your computer and use it in GitHub Desktop.

Select an option

Save aczw/cd1d5dcd380267e51ed23b89fc427c6e to your computer and use it in GitHub Desktop.
JS script for Matrix-like text animation on load
<blockquote class="berkeley animate-fade italic text-sweater-3 [--order:2]">
<p aria-live="polite" id="mewo-quote" class="mewo-quote h-4 w-fit -indent-1.5"></p>
</blockquote>
<script>
const speed = 40;
const size = 7;
const elt = document.querySelector<HTMLParagraphElement>("#mewo-quote")!;
const text = '"Waiting for something to happen?"';
const symbols = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()[]\\+-={}/";
function clampIndex(index: number) {
if (index <= 0) {
return 0;
} else if (index >= text.length - 1) {
return text.length - 1;
} else {
return index;
}
}
let numIterations = text.length + size;
let iterationIndex = 0;
let timer = window.setInterval(() => {
if (iterationIndex < numIterations) {
let startIndex = iterationIndex - (size - 1);
let endIndex = iterationIndex;
let garbledSize = clampIndex(endIndex) - clampIndex(startIndex);
if (startIndex <= clampIndex(endIndex)) {
garbledSize++;
}
let garbled = "";
for (let i = 0; i < garbledSize; i++) {
garbled += symbols.charAt(Math.floor(Math.random() * symbols.length));
}
let rest = text.slice(0, startIndex >= 0 ? startIndex : 0);
elt.innerText = rest + garbled;
} else {
clearInterval(timer);
}
iterationIndex++;
}, speed);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment