Issue
I am trying to move a box by letting the user click a button but I only want the user to be able to call the function once in 'javascript'.
function myMove() {
let id = null; let id2 = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 1);
function frame() {
if (pos == 250) {
clearInterval(id);
id2 = setInterval(backframe, 1);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
function backframe() {
if (pos == 0) {
clearInterval(id2);
id = setInterval(frame, 1);
} else {
pos--;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
Solution
To add an event listener, that just fires once, addEventListener
can accept 3 arguments: type, listener, and options.
options
is an object that has a property called once
, you have set it to true
.
Ex:
button.addEventListener('click', myMove, { once: true })
Answered By - Mina
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.