Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript mouseenter not firing when html onmouseenter does

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>
like image 526
Florian Pittet Comte Harbour Avatar asked May 05 '26 10:05

Florian Pittet Comte Harbour


1 Answers

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.

like image 63
Andy Avatar answered May 07 '26 00:05

Andy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!