Untitled
unknown
javascript
a year ago
2.4 kB
14
Indexable
<script>
const words = ['Student', 'Developer', 'Computer Engineer'];
let currentWordIndex = 0; // Track the index of the current word
let currentText = ''; // Track the current text being typed
let isDeleting = false; // Track whether we are typing or deleting
let typeSpeed = 150; // Speed for typing
let deleteSpeed = 75; // Speed for deleting
let pauseBeforeDeleting = 2000; // Pause before starting to delete the fully typed word
let pauseBetweenWords = 500; // Pause between deleting and typing the next word
function typeWriter() {
const currentWord = words[currentWordIndex]; // Get the current word based on the index
if (!isDeleting) {
// Typing logic - Add characters to the text
currentText = currentWord.substring(0, currentText.length + 1);
} else {
// Deleting logic - Remove characters from the text
currentText = currentWord.substring(0, currentText.length - 1);
}
// Update the text in the DOM
document.getElementById('typewriter').textContent = currentText;
// When the word is fully typed, start the deleting process after a pause
if (!isDeleting && currentText === currentWord) {
setTimeout(() => isDeleting = true, pauseBeforeDeleting);
}
// When the word is fully deleted, move to the next word
else if (isDeleting && currentText === '') {
isDeleting = false;
currentWordIndex = (currentWordIndex + 1) % words.length; // Move to the next word, loop back at the end
setTimeout(typeWriter, pauseBetweenWords); // Pause between words before typing the next one
return; // Exit the function to prevent immediate re-typing after deleting
}
// Set the appropriate typing or deleting speed
let speed = isDeleting ? deleteSpeed : typeSpeed;
// Call the function again to continue typing or deleting
setTimeout(typeWriter, speed);
}
// Start the typewriter effect after the page loads
document.addEventListener('DOMContentLoaded', typeWriter);
</script>Editor is loading...
Leave a Comment