Typwriter effect on text using java

i am trying to add typewriter animation to my html text as soon as the url loads, using the code below. Please check why this might not be working.

  <!DOCTYPE html>
    <html>
    <body>
    
    
    <p onload="typeWriter()" id="demo"></p>
    <style>
    p   {
      color: Black;
      font-family: arial;
      }
    </style>
    <script>
    var i = 0;
    var txt = 'Lorem ipsum dummy text blabla.';
    var speed = 50;
    
    function typeWriter() {
      if (i < txt.length) {
        document.getElementById("demo").innerHTML += txt.charAt(i);
        i++;
        setTimeout(typeWriter, speed);
      }
    }
    
    </script>
    
    </body>
    </html>

2 thoughts on “Typwriter effect on text using java”

  1. The onload="" attribute does not work on a <p> element (see here). I’d suggest doing that in JavaScript instead:

    var i = 0;
    var txt = 'Lorem ipsum dummy text blabla.';
    var speed = 50;
    
    function typeWriter() {
      if (i < txt.length) {
        document.getElementById("demo").innerHTML += txt.charAt(i);
        i++;
        setTimeout(typeWriter, speed);
      }
    }
    
    document.addEventListener("DOMContentLoaded", typeWriter);
    p   {
      color: Black;
      font-family: arial;
    }
    <p id="demo"></p>

    Alternatively you can specify onload on the <body> tag:

    <body onload="typeWriter()">
    
    Reply
  2. **The onload="" attribute does not work on p tag **

    var i = 0;
    var txt = 'Lorem ipsum dummy text blabla.';
    var speed = 50;
    
    document.addEventListener("DOMContentLoaded", typeWriter);
    function typeWriter() {
      if (i < txt.length) {
        document.getElementById("demo").innerHTML += txt.charAt(i);
        i++;
        setTimeout(typeWriter, speed);
      }
    }
    p{
      color: Black;
      font-family: arial;
      }
    <!DOCTYPE html>
    <html>
    <body>
    
    
    <p  id="demo"></p>
    
    
    
    </body>
    </html>
    Reply

Leave a Comment