i’m trying to change text content in a
tag of my html on click event , but the new text content just adds to the old text instead of replacing .
document.getElementById("div_Container").addEventListener("click", function Typer(){
var index = 0;
var text ="Hello there, I'm a college student and I have a keen eye for whacky and cheeky animations.";
var speed = 60;
function textEffect() {
if (index < text.length) {
document.getElementById("typing_Text").textContent += text.charAt(index);
index++;
setTimeout(textEffect, speed);
}
}
textEffect();
}, {once : true});
<div id="div_Container" class="d-grid gap-2 d-md-flex justify-content-md-start">
<p id="typing_Text">Click here to learn about me. </p>
</div>
i have tried replacing textContent with innerHtml .
3
Answers
try this:
First you put the function definition where it wants a function to call. So you should move
function Typer()
… outside of theaddEventListener
or make it into an anonymous/arrow function. Secondly adddocument.getElementById("typing_Text").textContent = '';
before callingtextEffect()
to remove the previous text.This is how you should do it if you want to remove the text before inserting the new one, just add that one line before the textEffect function. Just made a fiddle here with my solution in case you want to try it out. Hope this is what you are looking for.
}, {once : true});