Search code examples
jquerytwitter-bootstrapfocuspopover

jQuery - Twitter Bootstrap - close all popovers on body's any elements focus


I'm trying closing any popover is opened when any body element (not the popover itself) is focused,

so i do:

 $(document.body).on('focus focusout focusin', function(e) {
  if( e.target.classList.contains('popover') ){return false;}
  else{
    $('*').popover('hide');
  }
  // code to close the popover
});

this works great on Chrome but not on FF, on FF i need to focusin and focusout before the popover is closed.

here is my example working only for chrome: http://jsfiddle.net/CU5U5/4/

How can i fix this?


Solution

  • An alternative:

    $(document).on('focus', ':not(.popover)', function(){
        $('.popover').popover('hide');
    });
    

    Edit:

    So as it turns out, my above answer is incorrect. You need to call .popover('hide') on the element the popover was instantiated on... not the .popover itself. AND you need to stop propagation of the click event on the link (i.e., return false in click handler) so it doesn't bubble up to the document root. See this for an answer, http://jsfiddle.net/aFacG/1/.

    HTML

    <a data-content="a popover" id="mypopover" href="#">click me</a>
    

    JS

    $(document).ready(function(){
      $("#mypopover").popover();
    
      $(document).on('click', function(){
          $("#mypopover").popover('hide');
      });
    
      $('#mypopover').click(function(){
          return false;
      });
    });