javascripthtmlonloadonmouseover

How do i make a JavaScript event run on page load?


Im new to JS and replicated this effect according to a showcase of it that i saw which is supposed to "glitch" the text on hover and then make it go back to the original text. This works by using .onmouseover and running the event after that. I tried changing this to .onload but then it wont run the animation/effect and i can't figure out why it does not work.

Here is my code:

const symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"


document.getElementById("load-text").onmouseover = event => {
    let iterations = 0

   const interval = setInterval(() => {
    event.target.innerText = event.target.innerText.split("")
    .map((letter, index) => {
        if (index < iterations) {
            return event.target.dataset.value[index];
        }
        
        return symbols[Math.floor(Math.random() * 35)]
   })
    .join("");

    if(iterations >= event.target.dataset.value.length) clearInterval(interval);

    iterations += 1 / 6;
}, 30);
}
body {   
    height: 100vh;
    width: 100vw;
    margin: 0;
    overflow: hidden;
    display: flex;
    background-color: #121012;
    justify-content: center;
}
.loader{
    margin-top: 40vh;
    color: #EEEEEE;
    font-family: monospace;
    font-size: 30pt;

}
<div class="loader">
    <p id="load-text" data-value="LOADER"> LOADER </p>
</div>
    <script src="project.js"></script>
(code pen: https://codepen.io/Tesked/pen/ExedNQX)

I have tried using possible solutions in this thread How do I call a JavaScript function on page load? but none of them seem to work, the event still doesn't fire unless i add the .onmouseover Where it works as it is intended to.

The idea here is to use this as a "loading screen" of sort that will do the glitch effect and then fade in the rest of the page, though this is a problem for another time.


Solution

  • I made a small change on your JS code

    window.onload = function() {
      const symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
      const target = document.getElementById("load-text");
      let iterations = 0;
    
      const interval = setInterval(() => {
        target.innerText = target.innerText.split("")
          .map((letter, index) => {
            if (index < iterations) {
              return target.dataset.value[index];
            }
    
            return symbols[Math.floor(Math.random() * symbols.length)];
          })
          .join("");
    
        if (iterations >= target.dataset.value.length) clearInterval(interval);
    
        iterations += 1 / 6;
      }, 30);
    };
    

    i wrapped the function inside a window.onload tested on your pen seems working could you try this and see if this is what you are expecting