Created
January 21, 2021 15:02
-
-
Save el1s7/88e3413d389b36e10b740613b9233fac to your computer and use it in GitHub Desktop.
Text Shuffle / Roll Effect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Author: Elis | |
License: MIT | |
Usage: | |
Shuffler(element,{ | |
speed?: 20 // Shuffle speed in ms | |
limit?: 10 // Characters shuffle count per letter | |
text?: "Other" // Optionally pass another text | |
all?: true // Shuffle All Letters / Shuffle One letter at a time | |
}); | |
*/ | |
window.Shuffler = function(){ | |
function shuffleText(e,opt={}){ | |
const textElement = (typeof e === "string") ? document.querySelector(e) : e; | |
var realText = (opt.text || textElement.innerText).split(""); | |
var textType = realText.map(function(t){ return getTextRange(t.charCodeAt(0));}); | |
var randomText = realText.map(function(t,i){ return randomChar(textType[i]); }); | |
var randomGuesses = opt.limit || 10; | |
var randomInterval = opt.speed || 25; | |
var randomAll = opt.hasOwnProperty("all") ? opt.all : true; //Random All Letters / Random One letter at a time | |
var currentTextIndex = 0; | |
var currentGuessesIndex = 0; | |
var runInterval = setInterval(function(){ | |
if((currentTextIndex + 1) * randomGuesses === currentGuessesIndex){ | |
randomText[currentTextIndex] = realText[currentTextIndex]; | |
currentTextIndex+=1; | |
} | |
if(!randomText[currentTextIndex]){ | |
textElement.innerText = randomText.join(""); | |
clearInterval(runInterval); | |
return false; | |
} | |
currentGuessesIndex+=1; | |
if(randomAll){ | |
for(var x=currentTextIndex; x < realText.length; x++){ | |
randomText[x] = randomChar(textType[x]); | |
} | |
} | |
else{ | |
randomText[currentTextIndex] = randomChar(textType[currentTextIndex]); | |
} | |
textElement.innerText = randomText.join(""); | |
return true; | |
}, randomInterval); | |
} | |
//Random Letter from a ASCII char range | |
const randomChar = function(range) { | |
range = Array.isArray(range) ? range : [32,127]; | |
return String.fromCharCode(Math.floor(Math.random() * (range[1]-range[0] + 1) + range[0])); | |
} | |
//Get Letter Type from ASCII charCode | |
const getTextRange = function(n){ | |
var ascii = { | |
"upper": [65,90], | |
"lower": [97,122], | |
"number": [48,57], | |
"symbol": [33,47], | |
"space": [32,32] | |
}; | |
var currentRange = ascii.symbol; | |
for(var chars in ascii){ | |
var [a,b] = ascii[chars]; | |
if(n >= a && n <=b){ | |
currentRange = ascii[chars]; | |
break; | |
} | |
} | |
return currentRange; | |
} | |
return shuffleText.apply(this,arguments); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment