How to prevent mouse-leave for plugin icon?

118 Views Asked by At

I have a dropdownmenu which I hide/show with JS based on mouseleave and mouseenter event. I am using JS to hide the menu with a timeout, so a user with a shaky mouse does not accidentally close the menu.

I am also using the KeePassXC-Browser plugin. This creates a key-icon inside the password input field.

When I hover over the key-icon inside my dropdown menu, the mouseleave event is triggered.

enter image description here

Here is an example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Test</title>
  </head>
  <body>
  <div style="padding:20px;background-color:grey" id="wrapper">
        <input type="password">
  <div>
  
  <script>
  const wrapper = document.getElementById('wrapper');
  wrapper.addEventListener("mouseleave", function(event){
    console.log('LEAVING');
  });
  </script>
  </body>
</html>

How can I catch on mouse leave, that the plugin icon is hovered? Is there a general approach that also covers possible other plugins that add icons to input elements?

EDIT: Hint from Cbroe, the mouseleave is caused because the key icon is outside the wrapper and positioned absolute to appear on the input box: enter image description here

1

There are 1 best solutions below

0
Adam On

As said in comments from Cbroe, the mouseleave is caused because the key icon is outside the wrapper and positioned absolute to appear on the input box.

Also autocomplete from the input would trigger mouseleave as well.

To fix it, one could check in the mouseleave event if the mouse coordinates are still in the wrapper:

<script>
  const wrapper = document.getElementById('wrapper');
  wrapper.addEventListener("mouseleave", function(event){
      const wrapperBounding = wrapper.getBoundingClientRect();
        if (event.clientX >= wrapper.left && event.clientX <= wrapper.right &&
            event.clientY >= wrapper.top && event.clientY <= wrapper.bottom) {
            return
        }
        console.log('LEAVING');
  });
</script>