1👍
Take a look at following snippet:
const { ref, onMounted } = Vue
const app = Vue.createApp({
setup() {
const textArray = ref(["web developer", "UI/UX Designer", "Front End"]);
const typingDelay = ref(200);
const erasingDelay = ref(100);
const newTextDelay = ref(2000); // Delay between current and next text
let textArrayIndex = ref(0);
let charIndex = ref(0);
const typedTextSpan = ref(0);
const cursorSpan = ref(0);
function type() {
if (charIndex.value < textArray.value[textArrayIndex.value].length) {
if(!cursorSpan.value.classList.contains("typing")) cursorSpan.value.classList.add("typing");
typedTextSpan.value.textContent += textArray.value[textArrayIndex.value].charAt(charIndex.value);
charIndex.value++;
setTimeout(() => type(), typingDelay.value);
}
else {
cursorSpan.value.classList.remove("typing");
setTimeout(() => erase(), newTextDelay.value);
}
}
function erase() {
if (charIndex.value > 0) {
if(!cursorSpan.value.classList.contains("typing")) cursorSpan.value.classList.add("typing");
typedTextSpan.value.textContent = textArray.value[textArrayIndex.value].substring(0, charIndex.value - 1);
charIndex.value--;
setTimeout(() => erase(), erasingDelay.value);
}
else {
cursorSpan.value.classList.remove("typing");
textArrayIndex.value++;
if(textArrayIndex.value >= textArray.value.length) textArrayIndex.value = 0;
setTimeout(() => type(), typingDelay.value + 1100);
}
}
onMounted(() => setTimeout(() => type(), 1000))
return {
typedTextSpan, cursorSpan
}
},
})
app.mount('#demo')
p {
overflow: hidden;
}
.container p span.typed-text {
font-weight: normal;
color: white;
text-shadow:1px 1px 1px red;
}
.container p span.cursor {
display: inline-block;
background-color: #ccc;
margin-left: 0.1rem;
width: 3px;
animation: blink 1s infinite;
}
.container p span.cursor.typing {
animation: none;
}
@keyframes blink {
0% { background-color: #ccc; }
49% { background-color: #ccc; }
50% { background-color: transparent; }
99% { background-color: transparent; }
100% { background-color: #ccc; }
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div class="container">
<p>Im A'<span ref="typedTextSpan" class="typed-text"></span><span ref="cursorSpan" class="cursor"> </span></p>
</div>
</div>
Source:stackexchange.com