Assign the event handler function to a variable, or give it a proper name. Then add and remove that.
Your removeEventListener
call is failing because you're passing it a unique function.
Also, you actually don't want to undo the event listener to achieve the effect you want. Instead, listen to separate events: mouseover
and mouseout
. For example:
var btn = document.getElementById('btn');
var par = document.getElementById('par');
btn.addEventListener('mouseover', function (e) {
par.style.visibility = 'visible';
});
btn.addEventListener('mouseout', function (e) {
par.style.visibility = 'hidden';
});
<button id="btn">Hover over me</button>
<p id="par" style="visibility: hidden;">This shows when hovering over the button</p>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…