javascriptjquerytypedtypedjs

How to implement multi typed elements in single page with single function


I am a trying to two divs (that use stringElements) on the page that share the same class in typed.js, so far only the first occurence gets working.

Here, It is possible with 2 different function with different class. but, I want to it with single function with same class.

Here show you what i'm trying to do. https://jsfiddle.net/xbofduaz/

What would be the proper way for that.

var typed1 = new Typed('.typed', {
  stringsElement: '.typed-strings',
  loop: true,
  typeSpeed: 50,
  backSpeed: 20,
  backDelay: 1700,
  showCursor: false,
});

HTML

<div class="wrap">
  <h1>TypedJS on multiple identical stringElements on the page</h1>

  <div class="typed-strings">
    <p>Ice cream</p>
    <p>Moog synth</p>
    <p>Holidays in space</p>
  </div>
  <span class="typed"></span>

  <p> Some other stuff on the page goes on, until we uncounter the exact same typed strings, that I also want to animate (and tarket thanks to a class). To note that both of these similar blocks come from the database, I'm unable to duplicate them to change their class or id, I need them to be exactly the same, and both be animated. </p>

  <div class="typed-strings">
    <p>Ice cream</p>
    <p>Moog synth</p>
    <p>Holidays in space</p>
  </div>
  <span class="typed"></span> </div>

Solution

  • You can see that document.querySelector() is used in the load method of typedjs. So multiple elements cant be constructed. Try using querySelectorAll()

    document.querySelectorAll('.typed').forEach(function(el) {
        new Typed(el, {
        stringsElement: el.previousElementSibling,
        loop: true,
        typeSpeed: 50,
        backSpeed: 20,
        backDelay: 1700,
        showCursor: false,
      })
    });
    

    Working Demo

    https://jsfiddle.net/ebjzmLur/