Search code examples
javascripthtmlhoverhide

Override JS by hovering out of a div?


How can I modify this so that when I hover the pointer outside the button and search-list div, the search-list disappears? Currently, the search-list does not hide when hovering outside the div or button.

I understand that I probably need to adjust the JavaScript code, but I'm struggling to comprehend how to implement this. Thank you.

function ListToggle() {
  var L = document.getElementById("search-list");
  L.style.display = "block"; // <-- Set it to block
}
#search-list {
  width: 150px;
  height: 150px;
  background-color: aquamarine;
}
<button onclick="ListToggle()">Tests</button>

<div id="search-list" style="display:none">
  search-list
</div>


Solution

  • To do what you require you can hook a mousemove event to the document. In that event handler you can interrogate the event.target to see if it's the button trigger or the search list, if it's not, then hide the content.

    Note the use of addEventListener() in the JS instead of onX attributes in the HTML. The latter is bad practice and should be avoided where possible. In addition, note that I moved the CSS styling in to the stylesheet. Don't put CSS in your HTML.

    const button = document.querySelector('#trigger');
    const searchList = document.querySelector('#search-list');
    
    button.addEventListener('click', () => {
      searchList.style.display = "block";
    });
    
    const updateListState = e => {
      const targetId = e.target.id;
      if (targetId !== 'trigger' && targetId !== 'search-list') {
        searchList.style.display = "none";
      }
    }
    document.addEventListener('mousemove', updateListState);
    #search-list {
      width: 150px;
      height: 150px;
      background-color: aquamarine;
      display: none;
    }
    <button id="trigger">Tests</button>
    <div id="search-list">
      search-list
    </div>

    That being said, it would be possible to achieve your desired affect much more simply by using CSS alone, assuming that having the list appear when the mouse hovers the trigger button meets your requirements:

    #search-list {
      width: 150px;
      height: 150px;
      background-color: aquamarine;
      display: none;
    }
    
    #search-list:hover,
    #trigger:hover + #search-list {
      display: block;
    }
    <button id="trigger">Tests</button>
    <div id="search-list">
      search-list
    </div>