JSFiddle - React, Tailwind, and code Playground
by joplomacedo
HTML
<div class="switchingWord">
ombro
</div>
JavaScript
const words = [
];
const $word = document.querySelector('.switchingWord');
function getRandomNumBetween( num1, num2 ){
return Math.floor(Math.random() * num2) + num1;
}
function switchElTextLetterByLetter( $el, newText, typingSpeed, deleteSpeed, doneCb ) {
removeLettersFromElOneByOne($el, deleteSpeed, () => {
setTimeout( () => {
addLettersToElOneByOne( $el, newText, typingSpeed, doneCb);
}, getRandomNumBetween(...typingSpeed) + 500);
})
}
function removeLettersFromElOneByOne( $el, typingSpeed, doneCb ) {
const text = $el.innerText;
if ( text.length ) {
const newText = text.substring(0, text.length-1);
$el.innerText = newText;
if ( newText.length ) {
setTimeout( () => {
removeLettersFromElOneByOne($el, typingSpeed, doneCb)
}, getRandomNumBetween(...typingSpeed));
} else {
doneCb();
}
} else {
doneCb();
}
}
function addLettersToElOneByOne( $el, newText, typingSpeed, doneCb ) {
const currentText = $el.innerText;
const nextLetter = newText[currentText.length];
if ( nextLetter !== undefined ) {
$el.innerText += nextLetter;
if ( $el.innerText !== newText ) {
setTimeout(() => {
addLettersToElOneByOne($el, newText, typingSpeed, doneCb);
}, getRandomNumBetween(...typingSpeed));
} else {
doneCb();
}
} else {
doneCb();
}
}
function xyz( $el, {
textArr,
wordDisplayTime,
deleteSpeed,
typingSpeed,
currTextListIdx = 0
}) {
switchElTextLetterByLetter($el, textArr[currTextListIdx], typingSpeed, deleteSpeed, () => {
if ( currTextListIdx === textArr.length - 1) {
currTextListIdx = 0;
} else {
++currTextListIdx;
}
setTimeout( () => {
xyz($el, {
textArr,
wordDisplayTime,
typingSpeed,
deleteSpeed,
currTextListIdx
});
}, wordDisplayTime)
});
}
setTimeout( () => {
xyz($word, {
textArr: words,
...