I am a Javascript novice and have been working on a script and it works! It is a simple typewriter effect. I want to apply it to all elements with the .type-me class attached. Using querySelector, I got it to work on the first element but I’m not sure how to amend the script so that it works on any element that has the .type-me class attached. Any assistance would be greatly appreciated.
<script>
var i = 0;
var txt = document.querySelector('.type-me').textContent;
document.querySelector('.type-me').textContent = '';
document.querySelector('.type-me').removeAttribute('style');
var speed = 500;
type();
function type() {
if (i < txt.length) {
document.querySelector('.type-me').textContent += txt.charAt(i);
i++;
setTimeout(type, speed);
}
}
</script>
I’ve tried using a combination of document.getElementsbyClassName and document.querySelectorAll but I have a feeling a loop is needed and I’m not great at writing loops just yet.
2
Answers
You are correct that a loop is needed.
First, you’ll need to gather all the DOM elements with the class into a node list and then you can loop over that and add the event handler:
Something like this:
Add an event handler to all the
type-me
class elements. Then in the event handler, use the current element being triggered’s value to update the rest of thetype-me
elements.Code with a demo.
Demo