Search code examples
javascriptfunctionencodingvar

add background color to text for a second with a delay


I have this script that types text itself, then deletes it and type from the beginning. Here is an example https://typedjs.webflow.io

<script>
  var typed = new Typed(".typed-words", {
  strings: ["Hello, my name is John."],
  typeSpeed: 75,
  backSpeed: 10,
  backDelay: 800,
  startDelay: 500,
  loop: true,
  showCursor: false,
  cursorChar: "|",
  attr: null,
});
</script>

so it shoes the typeSpeed 75. which means that the the phrase "Hello, my name is John." will be typed until the end in 75 whatever units.

question: is there a way to add a background color to the phrase once it finished typing itself? so let's say the phase "Hello, my name is John." finished typing, its background color becomes blue for a second and the phrase deletes itself and starts typing from the beginning? Here is an example of this background color change: https://marcusts.com/demo/

thank you


Solution

  • I've used onStringTyped method to do this task (I found it from their documentation). You can check my example.

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    <style>
      .last-word {
        color: #299CDF;
      }  
      
    </style>
    <body>
      
      <div class="typed-words"></div>
    
      
      <script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11"></script>
      <script>
        console.clear();
        var typed = new Typed(".typed-words", {
          strings: ["Hello, my name is <span class='last-word'>John.</span>", "Hello, my name is <span class='last-word'>Lisa.</span>", "Hello, my name is <span class='last-word'>Beetlejuice.</span>"],
          typeSpeed: 75,
          backSpeed: 50,
          backDelay: 800,
          startDelay: 500,
          loop: true,
          showCursor: false,
          cursorChar: "|",
          attr: null,
          onStringTyped: function(pos, self) {
            const lastWord = document.querySelector('.last-word');
            lastWord.style.background = '#7bfde7';
          }
        });
      </script>
    </body>
    </html>