I have a code when hovering over the button, it prints a letter on the website. How can I make this hovering happen only once? What I really want to do is hover then the function called a will only be performed once This is the code:
function a(){
document.body.innerHTML = 'uu';
}
</script>
<button onm ouseOver="a()">hello world</button>
CodePudding user response:
Rather than using the onmouseover attribute, attach the handler from Javascript and specify the once option:
let count = 0;
const a = function() {
document.getElementById('btnTest').innerHTML = `Button hovered ${ count} times`;
document.body.innerHTML = 'uu';
};
window.addEventListener('DOMContentLoaded', () => {
document.getElementById('btnTest').addEventListener('mouseover', a, {
once: true
});
});
<button id="btnTest">This is the button</button>
EventTarget.addEventListener() - Web APIs | MDN
CodePudding user response:
Give your control an id to target, and then remove the attribute after you hover:
function a() {
document.body.innerHTML = 'uu';
let c = document.getElementById("btnTest");
c.removeAttribute('onmouseover');
}
<button id="btnTest" onm ouseOver="a()">hello world</button>
This will only allow the function to run once per page load, so if you need it to work after removing and replacing the mouse again, we will need to adjust it.
CodePudding user response:
It should even if you stop hovering and come back and still not refresh the page it will work
