So i'm very new with javascript and been trying to make a function code that only work only once.
this is my logo that i've been trying to animate it.
<img src="img/logot2.png" id="logoutjs" onm ouseover="move()" alt="Logo" width="100" height="30" style="position: absolute; right: 8px;" >
and this is the javascript.
<script>
var id = null;
function move() {
var elem = document.getElementById("logoutjs");
var pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == -110) {
clearInterval(id);
} else {
pos--;
elem.style.left = pos 'px';
}
}
move(){};
}
</script>
CodePudding user response:
Remove onmouseover
attribute from image
<img src="img/logot2.png" id="logoutjs" alt="Logo" width="100" height="30" style="position: absolute; right: 8px;" >
Then use addEventListener
with {once: true}
let img = document.querySelector("#logoutjs");
img.addEventListener("mouseover", move, {once: true})
var id = null;
function move() {
var elem = document.getElementById("logoutjs");
var pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == -110) {
clearInterval(id);
} else {
pos--;
elem.style.left = pos 'px';
}
}
}
CodePudding user response:
Maybe one problem is the function call at the bottom of the function definition? I would suggest omitting the move() {}
One other thing is that you don't have to use the document.getElementById
. You should be able to access the image by adding event as a parameter in your function and using event.target.
If you want the function to work only once and then never again, remove the eventhandler at the bottom of the function.
<img src="img/logot2.png" id="logoutjs" onm ouseover="move(event)" alt="Logo" width="100" height="30" style="position: absolute; right: 8px;" >
<script>
var id = null;
function move(event) {
var pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == -110) {
clearInterval(id);
} else {
pos--;
event.target.style.left = pos 'px';
}
}
event.target.removeAttribute("onmouseover");
}
</script>