Search code examples
htmlcssdrop-down-menudropdown

how to close the dropdown button when user click white space?


I would like to close dropdown button when user click a outside space. How to control it ?

https://stackblitz.com/edit/js-as5io9?file=index.html


Solution

  • You could add click event listener to the window.

    When the window is clicked, the listener will set the checked of checkbox to false and close the dropdown menu.

    Here is the code:

    let checkbox = document.querySelector('#delete-drop-down');
    
    window.addEventListener('click', ()=>{
      checkbox.checked = false;
    });
    
    
    checkbox.addEventListener('click', event=>{
      event.stopPropagation();
    });
    

    event.stopPropagation() stops the click event on checkbox propagate to the window. So that the dropdown menu will not be closed immediately。