Scramble Text
by smombartz
HTML
<a class="scramble" href="#">car</a>
CSS
html, body {
box-sizing: border-box;
font-size: 12px;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
background: #fff;
width: 100%;
height: 100%;
padding: 10px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body * {
box-sizing: border-box;
}
h1 {
position: absolute;
bottom: 10px;
font-size: 16px;
font-weight: bold;
color: #ccc;
}
a.website {
position: absolute;
bottom: 10px;
right: 10px;
}
a {
color: #000;
text-decoration: none;
font-family: 'Courier New', Courier, monospace;
font-size: 14px;
text-transform: uppercase;
letter-spacing: .1em;
}
p {
//text-transform: uppercase;
color: #888;
margin-bottom: 30px;
}
JavaScript
document.addEventListener('DOMContentLoaded', function() {
// Set effect velocity in ms
var velocity = 50;
var scrambleElements = document.querySelectorAll('.scramble');
scrambleElements.forEach(function(item) {
item.setAttribute('data-text', item.textContent);
scrambleText(item); // Initially scramble the text
});
// Helper function to generate a random character
function getRandomChar() {
const alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return alphabet[Math.floor(Math.random() * alphabet.length)];
}
// Shuffle function to replace part of the text with random characters
function scramble(text) {
return text.split('').map(() => getRandomChar()).join('');
}
function scrambleText(element) {
var originalText = element.getAttribute('data-text');
var index = 0;
var interval = setInterval(function() {
if (index >= originalText.length) {
clearInterval(interval);
} else {
element.textContent = scramble(originalText.substring(0, index + 1)) + originalText.substring(index + 1);
index++;
}
}, velocity);
}
function unscrambleText(element, originalText) {
var textArray = originalText.split('');
var index = 0;
var interval = setInterval(function() {
if (index >= originalText.length) {
clearInterval(interval);
element.textContent = originalText; // Ensure final text is the original one
} else {
element.textContent = originalText.substring(0, index + 1) + scramble(originalText.substring(index + 1));
index++;
}
}, velocity);
}
scrambleElements.forEach(function(element) {
element.addEventListener('mouseenter', function() {
unscrambleText(element, element.getAttribute('data-text'));
...