DEV Community

ktr92
ktr92

Posted on

[html css jquery] How to hide element by click outside

There is an element which we need to close by click outside of it. We can do it using simple reusable function.

codepen demo: https://codepen.io/ktr92/pen/LYgyGaY

Solution example

HTML

<div>
  <button data-toggleclick="block1">Open block 1</button>
  <div data-toggleblock="block1" class="active">
     Click outside to close
  </div>
  <div>
    <br><br>
  <button data-toggleclick="block2" >Open block 2</button>
    <div data-toggleblock="block2"  class="active">
      Click outside to close
    </div>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS

[data-toggleblock] {
  display: none;
}

[data-toggleblock].active {
  display: block;
}
Enter fullscreen mode Exit fullscreen mode

JS (jquery)
We need a second argument (our element's open button) to prevent the element from opening and closing at the same time.

function closeByClickOutside(element, button, callback) {
    $(document).click(function(event) {
        if (!$(event.target).closest(`${element},${button}`).length) {
            $(button).removeClass('active')
            $(element).removeClass('active')
            // or  
            //$(element).hide()
        }
    });

    $(document).keyup(function(e) {
        if (e.key === "Escape") { // escape key maps to keycode `27`
            $(button).removeClass('active')
            $(element).removeClass('active')
            // or  
            //$(element).hide()
        }
    });

    if (callback instanceof Function) { callback(); }
  }

// usage
closeByClickOutside('[block_selector]', '[button_selector]')
Enter fullscreen mode Exit fullscreen mode

Top comments (0)