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
The issue is that the
typewriter
variable is not declared in the function scope. This means that the function does not have access to thetypewriter
object, and therefore cannot call thedeleteAll()
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:This will create a local variable called
typewriter
in the function scope. The function will now be able to access thetypewriter
object and call thedeleteAll()
method.The following code shows the corrected code:
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.