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

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay