[javascript] How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?

This should work in Bootstrap 4:

_x000D_
_x000D_
$("#my-popover-trigger").popover({_x000D_
  template: '<div class="popover my-popover-content" role="tooltip"><div class="arrow"></div><div class="popover-body"></div></div>',_x000D_
  trigger: "manual"_x000D_
})_x000D_
_x000D_
$(document).click(function(e) {_x000D_
  if ($(e.target).closest($("#my-popover-trigger")).length > 0) {_x000D_
    $("#my-popover-trigger").popover("toggle")_x000D_
  } else if (!$(e.target).closest($(".my-popover-content")).length > 0) {_x000D_
    $("#my-popover-trigger").popover("hide")_x000D_
  }_x000D_
})
_x000D_
_x000D_
_x000D_

Explanation:

  • The first section inits the popover as per the docs: https://getbootstrap.com/docs/4.0/components/popovers/
  • The first "if" in the second section checks whether the clicked element is a descendant of #my-popover-trigger. If that is true, it toggles the popover (it handles the click on the trigger).
  • The second "if" in the second section checks whether the clicked element is a descendant of the popover content class which was defined in the init template. If it is not this means that the click was not inside the popover content, and the popover can be hidden.

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation