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
You can use
window.onload
:The simplest is probably completey ditching the eventhandler and doing
and include this script at the end of your HTML. This way, it will be executed after all HTML has been rendered