DEV Community

ktr92
ktr92

Posted on

2

[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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs