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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

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

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay