skip to Main Content

There seems to be some kind of issue with Typewriter JS scoping. For instance, in the following code, deleteAll() executes no problem

const typewriter = new Typewriter('#typewriter');

typewriter.start();
typewriter.typeString('Hello, world');
typewriter.deleteAll();
<script src="https://unpkg.com/typewriter-effect@latest/dist/core.js"></script>
<div id="typewriter"></div>

however, when deleteAll() is put inside a function, it does not work.

const typewriter = new Typewriter('#typewriter');

typewriter.start();
typewriter.typeString('Hello, world');

const yes = document.querySelector("#yes");
yes.addEventListener('click', function() {
  typewriter.deleteAll();
});
<script src="https://unpkg.com/typewriter-effect@latest/dist/core.js"></script>
<div id="typewriter"></div>

<button id="yes">yes</button>

All the code is called after DOM content is loaded. Does anyone know what the issue is or how I can fix it?

2

Answers


  1. The issue is that the typewriter variable is not declared in the function scope. This means that the function does not have access to the typewriter object, and therefore cannot call the deleteAll() method.

    To fix this, you need to declare the typewriter variable in the function scope. You can do this by adding the following line to the function:

    let typewriter = document.getElementById("typewriter");
    

    This will create a local variable called typewriter in the function scope. The function will now be able to access the typewriter object and call the deleteAll() method.

    The following code shows the corrected code:

    let yes = document.getElementById("yes");
    let no = document.getElementById("no");
    
    function onYesClick() {
      let typewriter = document.getElementById("typewriter");
      typewriter.deleteAll();
    }
    
    yes.addEventListener("click", onYesClick);
    
    Login or Signup to reply.
  2. There is some weird bug in the typewriter code. You might want to report it that it seems to not restart after it is done.

    Seems like it you call stop, with a pause, and start it will allow it to run.

    const typewriter = new Typewriter('#typewriter');
    
    typewriter.start();
    typewriter.typeString('Hello, world');
    
    const yes = document.querySelector("#yes");
    yes.addEventListener('click', function() {
      typewriter.stop().pauseFor(1).start().deleteAll();
    });
    <script src="https://unpkg.com/typewriter-effect@latest/dist/core.js"></script>
    <div id="typewriter"></div>
    
    <button id="yes">yes</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search