skip to Main Content

I am trying to make this script work on page load and not on mouseover and I tried many things none as worked

const letters = "ABCDEFGHKLMNOPQRSTUVWXYZ";

let interval = null;

document.querySelector("h1#scramble").onmouseover = event => {
  let iteration = 0;

  clearInterval(interval);

  interval = setInterval(() => {
    event.target.innerText = event.target.innerText
      .split("")
      .map((letter, index) => {
        if (index < iteration) {
          return event.target.dataset.value[index];
        }

        return letters[Math.floor(Math.random() * 20)]
      })
      .join("");

    if (iteration >= event.target.dataset.value.length) {
      clearInterval(interval);
    }

    iteration += 1 / 2;
  }, 6);
}
<h1 id="scramble" data-value="Hello">Helloword</h1>

I have tried to change the .onmouseover to .onload but that did not work

2

Answers


  1. You can use window.onload:

    const letters = "ABCDEFGHKLMNOPQRSTUVWXYZ";
    
    let interval = null;
    
    window.onload = () => {
      let text = document.querySelector("h1#scramble");
      let iteration = 0;
    
      clearInterval(interval);
    
      interval = setInterval(() => {
        text.innerText = text.innerText
          .split("")
          .map((letter, index) => {
            if (index < iteration) {
              return text.dataset.value[index];
            }
    
            return letters[Math.floor(Math.random() * 20)]
          })
          .join("");
    
        if (iteration >= text.dataset.value.length) {
          clearInterval(interval);
        }
    
        iteration += 0.5;
      }, 6);
    }
    <h1 id="scramble" data-value="Hello">Helloword</h1>
    Login or Signup to reply.
  2. The simplest is probably completey ditching the eventhandler and doing

    function scramble() {
      let elem = document.querySelector("#scramble");
      let iteration = 0;
      clearInterval(interval);
    
      interval = setInterval(() => {
        elem.innerText = elem.innerText
          .split("")
          .map((letter, index) => {
            if (index < iteration) {
              return elem.dataset.value[index];
            }
    
            return letters[Math.floor(Math.random() * 20)]
          })
          .join("");
    
        if (iteration >= elem.dataset.value.length) {
          clearInterval(interval);
        }
    
        iteration += 1 / 2;
      }, 6);
    }
    
    scramble()
    

    and include this script at the end of your HTML. This way, it will be executed after all HTML has been rendered

    <html>
    <head>
    ...
    </head>
    <body>
      ...
      <script>
        function scramble() {
          ...
        }
        scramble();
      </script>
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search