#why is my function not looping? its stuck on the first letter of the array

4 messages · Page 1 of 1 (latest)

median jay
#

porting over my site from 11ty to astro, thats why there's DOM manipulation code thats commented out. i thought switching to a simple variable would do the trick. buts just stuck on "B"

---
const words = ["Bob Smith.", "A Frontend Developer."];
let i = 0;
let counter;
let test = "";
const typeNow = () => {
  let word = words[i].split("");
  const loopTyping = () => {
    if (word.length > 0) {
      /* document.getElementById("text").innerHTML */
      test += word.shift();
    } else {
      setTimeout(() => {
        deleteNow();
      }, 700);
      return;
    }
    counter = setTimeout(loopTyping, 150);
  };
  loopTyping();
};
const deleteNow = () => {
  let word = words[i].split("");
  let test = "";
  const loopDeleting = () => {
    if (word.length > 0) {
      word.pop();
      /* document.getElementById("text").innerHTML */
      test = word.join("");
    } else {
      if (words.length > i + 1) {
        i++;
      } else {
        i = 0;
      }
      typeNow();
      return;
    }
    counter = setTimeout(loopDeleting, 100);
  };
  loopDeleting();
};
typeNow();
---

<div class="textContainer">
  <h3>Hello<span>!</span></h3>
  <div class="animationContainer">
    <h1 id="start">I Am</h1>
    <h1 id="text">{test}</h1>
    <h1>|</h1>
  </div>
</div>
median jay
#

so far i fixed it by moving the javascript to a .js file and then importing it like this in a small <Greeting /> component.

not sure if i like this solution...

<div class="textContainer">
  <h3>Hello<span>!</span></h3>
  <div class="animationContainer">
    <h1 id="start">I Am</h1>
    <h1 id="text"></h1>
    <h1>|</h1>
  </div>
  <script src="../scripts/typingAnimation.js"></script>
</div>
true spear
#

I think you could use a <script /> tag directly into your .astro file. But to explain, Astro is executed server-side when running between --- so it's not really suited for animation on the client-side afterward as no JS is shipped