Search code examples
javascripthtmltwitter-bootstrappopover

Complex Bootstrap 2 Popovers Click to Dismiss


I have multiple unique popovers on a page, need to hide them when clicking anywhere but the popover current active. The popovers are a little more complex than the standard implementation, so what I know do to make them hide doesn't apply.

http://jsfiddle.net/bb37385m/

$('.popover-markup > .trigger').popover({
    html : true,
    title: function() {
      return $(this).parent().find('.head').html();
    },
    content: function() {
      return $(this).parent().find('.content').html();
    },
    container: 'body',
    placement: 'right'
});

Solution

  • For that, you need to get your clicked element.

    var objclass = $(event.target).attr('class');
    

    We want the popup to disappear if clicked anywhere but itself. So we need to check if the click event is at anywhere on popup.

    $(event.target).closest('.popover').length == 1
    

    @bootstrap, to remove the popover use .popover('hide');

    Result;

    $(document).click(function(event) {
      var objclass = $(event.target).attr('class');
      if($(document).find('.popover').length > 0 && ($(event.target).closest('.popover').length == 1)){
          return false;
      }
      if ($(document).find('.popover').length > 0 && (objclass != 'trigger') && $(event.target).closest('.popover').length != 1) {
        $('.trigger').popover('hide');
      }
    
    });