When using the above code, "mouseenter" and "mouseleave" are fired once at start. "onmouseenter" and "onmouseleave" are fired when expected. How do I make "mouseenter" and "mouseleave" fire when expected ?
<!DOCTYPE html>
<html>
<body>
<div id="banner" style="border: 2px solid black; height: 200px"></div>
<div style="border: 2px solid black; height: 200px"></div>
<script>
var banner = document.getElementById("banner");
banner.setAttribute("onmouseenter", 'console.log("onmouseenter")');
banner.setAttribute("onmouseleave", 'console.log("onmouseenter")');
banner.addEventListener("mouseenter", console.log("mouseenter"));
banner.addEventListener("mouseleave", console.log("mouseleave"));
</script>
</body>
</html>
The event listener accepts a function that it will fire when the event happens. At the moment you're calling console.log immediately, rather than waiting for the event to fire. If you place the console logs inside a function this won't happen.
banner.addEventListener("mouseenter", function() {
console.log("mouseenter");
});
banner.addEventListener("mouseleave", function() {
console.log("mouseleave");
});
On a side note that's the second time this week I've seen setAttribute used with onclick. I would advise against using that method and stick with addEventListener.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With