skip to Main Content

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


  1. 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:

    document.querySelectorAll(".type-me").forEach(function(element){
      element.addEventListener("mouseover", function(event){
        // code that you want each element with the class to have
        // when it is hovered over.
      });
    });
    Login or Signup to reply.
  2. 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 the type-me elements.

    Code with a demo.

    import './style.css'
    
    document.querySelector('#app').innerHTML = `
    <textarea class="type-me"></textarea> </br>
    <textarea class="type-me"></textarea> </br>
    <textarea class="type-me"></textarea> </br>
    <textarea class="type-me"></textarea> </br>
    `
    // grab all the type-me class elements
    const targets = document.querySelectorAll('.type-me');
    for(let i = 0; i < targets.length; i++){
      const target = targets[i];
      // and add an event handler to each one
      target.addEventListener("input", onChange)
    }
    
    // the event handler
    function onChange(eventElement){
       // go through each element 
       for(let i = 0; i < targets.length; i++){
        const target = targets[i];
        // check that the current target is not the 
        // eventElement
        if(eventElement.target !== target) {
          // assign the eventElement's value to the target's
          const value = eventElement.target.value;
          target.value = eventElement.target.value;
        }  
      }
    }
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search