0

I am implementing popovers, since the existing libraries are not flexible enough. I want to set any div with a class .popover and it shows the behaviors:

  1. destroy on escape key
  2. destroy when clicks outside borders

Both are events, and both need to apply on elements classed as .popover. To destroy popovers on escape:

$(document).keyup(function(e) {

  if (e.keyCode == 27) { 
    popovers = $(".popover");
    //destroy popovers
 }
});

But I am stuck with how to listen in to mouse clicks globally and determining if they happened outside of a .popover.

SO answers mention having a global click listener that destroys all .popovers and adding a click listener to each popover that halts event propagation to the global listener.

But I want to define it only once globally, not once for every single popover I make. How do I do that?

Community
  • 1
  • 1
Jesvin Jose
  • 22,498
  • 32
  • 109
  • 202

2 Answers2

0
$('body').click(function(e) {
  if(!$(e.target).hasClass("popover")) { 
       //if element does not have a ".popover" class => it's outside
   $(".popover").remove();
  }
});

where e.target is the element you clicked on

user733421
  • 497
  • 4
  • 14
0
  1. You can create a div covering the whole page with z-index -1.
  2. On popover you can bring it to front
  3. Register popover closing onclick event on that div
  4. On popover close, bring it back behind all elements.
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169