skip to Main Content

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


  1. try this:

    function textEffect() {
        if (index < text.length) {
            document.getElementById("typing_Text").innerText+= text.charAt(index);
            index++;
            setTimeout(textEffect, speed);
        }
        
    }
    textEffect();
    
    Login or Signup to reply.
  2. First you put the function definition where it wants a function to call. So you should move function Typer()… outside of the addEventListener or make it into an anonymous/arrow function. Secondly add document.getElementById("typing_Text").textContent = ''; before calling textEffect() to remove the previous text.

    Login or Signup to reply.
  3. 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.

    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;
    // SIMPLY ADD THE LINE BELOW
    document.getElementById("typing_Text").textContent = "";
    function textEffect() {
        if (index < text.length) {
            document.getElementById("typing_Text").textContent += text.charAt(index);
            index++;
            setTimeout(textEffect, speed);
        }
        
    } 
    textEffect();
    

    }, {once : true});

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search