How can I make the onMouseOver function run only once? | Html
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 onMouseOver="a()">hello world</button>
Solution 1:
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