Skip to content
Advertisement

Only do click function if element is visible

So I have a search “modal box” (own html + css, not bootstrap) at the top of my page. When i click the search bar I want to open the modal box. Then when it is opened, I want to make it closable by clicking the “X” button or anywhere outside of the modal box.

Opening the modal box and closing it by pressing the button works with this snippet:

<script  type="text/javascript">
  var search_box =  document.querySelector('#search-box-top');
  var search_box_bg =  document.querySelector('#search-box-top-bg');

  document.querySelectorAll('#close-search-box').forEach(el => el.addEventListener('click', function() {
    search_box.style.display = 'none';
    search_box_bg.style.display = 'none';
  }))

  document.querySelectorAll('#open-search-box').forEach(el => el.addEventListener('click', function() {
    search_box.style.display = 'block';
    search_box_bg.style.display = 'block';
  }))   
</script>   

Now I have this code to see if a click happens inside the modal box or outside the modal box:

 var specifiedElement = document.getElementById('search-box-top');
 var search_box_visible = document.getElementById('search-box-top').style.display;

if (search_box_visible = 'none') {
document.addEventListener('click', function(event) {
    var isClickInside = specifiedElement.contains(event.target);
    if (isClickInside) {
     console.log('You clicked inside')
    }
    else {
      console.log('You clicked outside')
    }
});
} else {

}

The problem is the second function also works when the modal box is still closed, so the console always logs “You clicked outside”. So I need when search_box_visible = none that isClickInside works and when it is block it should return the else function of setting display = ‘none’;

Does anyone know how to combine these two or make a completely better function to do this? Thanks in advance!

Advertisement

Answer

Make sure you’re checking the display value inside the click event. Also, you can use the .closest() method to check if the click is happening inside or outside the modal. I made sure to include the open button in the check as well.

 document.addEventListener("click", function(event) {
    var search_box_visible = search_box.style.display;
    if(search_box_visible !== 'none'){
      if (event.target.closest('#search-box-top') || event.target.closest('#open-search-box')) {
        console.log("inside")
      } 
      else{
        console.log("outside")
        //search_box.style.display = "none";
      }         
    }
  });
Advertisement