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.
3
Answers
You have to a couple more steps but the
DOMContentLoaded
event works for this. In order to then target it, you also need to search for the element in your DOM becauseevent.target
will be the document.I made a small change on your JS code
i wrapped the function inside a
window.onload
tested on your pen seems workingcould you try this and see if this is what you are expecting
Simply trigger the event via: