Hide a popup on clicking outside the popup area


#1

Not sure how I’d do this with Stimulus:

var box = document.querySelector(".box");

// Detect all clicks on the document
document.addEventListener("click", function(event) {
	// If user clicks inside the element, do nothing
	if (event.target.closest(".box")) return;

	// If user clicks outside the element, hide it!
	box.classList.add("js-is-hidden");
});

Any suggestions would be appreciated.

Thanks! :slight_smile:


#2

I have something like this where this.bodyElement is just the body tag and this.closeSidebar() a function that removed classes (in my case it’s a sidebar overlay instead of a modal but does the same thing.

_canClose() {
  const outsideClickListener = event => {
    if (!event.target.closest('.form-sidebar')) {
      this.closeSidebar();
      removeClickListener();
    }
  };

  const removeClickListener = () => {
    this.bodyElement.removeEventListener('click', outsideClickListener);
  };

  this.bodyElement.addEventListener('click', outsideClickListener);
}

#3

I was thinking along similar lines, but was just wondering if there was something achievable with the data-action/targers :grimacing:


#4

Yep, you can use a data-action="click@window->controller-name#hide", like here:


#5

Awesome! :sunglasses:

Thanks for the replies all :smile:


#6

@pasacallaliberte the only issue seems to be that I can’t click an element inside the dropdown (I have an input) without triggering the hide - any suggestions?

e.g. code is here: https://codepen.io/askalot/pen/PQmEXL - but I am unable to get it to work as the static target = [‘menu’,‘button’] line is throwing an error in CodePen.