48

I am trying to manually close a bootstrap popover to get it to close when I click anywhere on the document or body that isn't the popover.

The closest thing I have found to accomplishing this is to create a directive (found this answer) but this is for a manual trigger if a variable is true or false.

Could anyone help me figure out how to to get it to close if I click on anything that isn't the popover?

I don't mind using jQuery $(document).click(function(e){}); I just have no clue how to call a close.

<div id="new_button" popover-template="plusButtonURL" popover-placement="right" popover-append-to-body="true" popover-animation="false">+</div>

Normally popover-trigger="focus" would do the trick, however my popover contains content that needs to be clicked on. I have an ng-click inside my popover that get's ignored if I use the focus trigger so I am looking for a not-so-conventional way to get around that.

Community
  • 1
  • 1
bryan
  • 8,879
  • 18
  • 83
  • 166

12 Answers12

42

UPDATE: With the 1.0 release, we've added a new trigger called outsideClick that will automatically close the popover or tooltip when the user clicks outside the popover or tooltip.

Starting with the 0.14.0 release, we've added the ability to programmatically control when your tooltip/popover is open or closed via the tooltip-is-open or popover-is-open attributes.

icfantv
  • 4,523
  • 7
  • 36
  • 53
  • 4
    is there an example of how to use `popover-is-open` to close popover when clicking outside it anywhere? – MattDionis Sep 29 '15 at 18:48
  • 1
    @MattDionis If the value of `popover-is-open` evaluates to true, then the dialog will be open. You can control this by a scope variable for example. – Martin van Driel Oct 20 '15 at 12:58
  • 1
    @MattDionis, we've added this ability. it's currently available in `master` and is targeted for the 1.0 release. There's a new trigger called `outsideClick`. – icfantv Dec 02 '15 at 17:32
  • Someone should add this to the documentation... I finally found it in the source :( – r0m4n Sep 15 '16 at 23:16
  • @r0m4n, what do you mean by "this"? It is in our documentation. Both in http://angular-ui.github.io/bootstrap/#/popover and http://angular-ui.github.io/bootstrap/#/tooltip. – icfantv Sep 16 '16 at 23:01
  • ah thanks, I must have missed that... I read through all the settings (apparently not close enough). Triggers apparently have its own section outside of the settings but anyhow, I see it now! Also, the docs say "What should trigger a show of the popover?" Which isn't exactly true for this... This is what triggers a hide of the popover – r0m4n Sep 16 '16 at 23:43
30

Since Angular UI Bootstrap 1.0.0, there is a new outsideClick trigger for tooltips and popovers (introduced in this pull request. In Angular UI Bootstrap 2.0.0, the popover-trigger has been modified to use angular expressions (Changelog), so the value has to be put in quotes. This code will work with current versions of angular-ui:

<div id="new_button" uib-popover-template="plusButtonURL" popover-trigger="'outsideClick'"
    popover-placement="right" popover-append-to-body="true" popover-animation="false">+</div>

This code will work with old versions of Angular UI Bootstrap (before 2.0.0):

<div id="new_button" uib-popover-template="plusButtonURL" popover-trigger="outsideClick"
    popover-placement="right" popover-append-to-body="true" popover-animation="false">+</div>
cdauth
  • 6,171
  • 3
  • 41
  • 49
24

EDITED:

Plunker Demo

Here's how it works (the still long and exhaustive explanation):

  1. Create a custom directive that allows you to target the trigger element.
  2. Create a custom directive that is added to the body and will find the trigger element and fire the custom event when it is clicked.

Create a custom directive to target the trigger element:

You need to trigger the custom event handler from the element that opened the popover (in the demo this is the button). The challenge is that the popover is appended as a sibling to this element and I always think that things have greater potential to break when you are traversing the DOM and expecting it to have a specific structure. There are several ways you can target the trigger element, but my approach is to add a unique classname to the element (I choose 'trigger') when you click on it. Only one popover can be opened at a time in this scenario, so it's safe to use a classname, but you can modify to suit your preference.

Custom Directive

app.directive('popoverElem', function(){
  return{
    link: function(scope, element, attrs) {
      element.on('click', function(){
        element.addClass('trigger');
      });
    }
  }
});

Applied to button

<button popover-template="dynamicPopover.templateUrl" popover-title="{{dynamicPopover.title}}" class="btn btn-default" popover-elem>Popover With Template</button>

Create a custom directive for the document body (or any other element) to trigger the popover close:

The last piece is to create a custom directive that will locate the triggering element and fire the custom event to close the popover when the element it is applied to is clicked. Of course, you have to exclude the initial click event from the 'trigger' element, and any elements you want to interact with on the inside of your popover. Therefore, I added an attribute called exclude-class so you can define a class that you can add to elements whose click events should be ignored (not causing the popover to close).

To clean things up, when the event handler is triggered, we remove the trigger class that was added to the trigger element.

app.directive('popoverClose', function($timeout){
  return{
    scope: {
      excludeClass: '@'
    },
    link: function(scope, element, attrs) {
      var trigger = document.getElementsByClassName('trigger');

      function closeTrigger(i) {
        $timeout(function(){ 
          angular.element(trigger[0]).triggerHandler('click').removeClass('trigger'); 
        });
      }

      element.on('click', function(event){
        var etarget = angular.element(event.target);
        var tlength = trigger.length;
        if(!etarget.hasClass('trigger') && !etarget.hasClass(scope.excludeClass)) {
          for(var i=0; i<tlength; i++) {
            closeTrigger(i)
          }
        }
      });
    }
  };
});

I added this to the body tag so that the entire page* acts as a dismissible backdrop for the popover:

<body popover-close exclude-class="exclude">

And, I added the exclude class to the input in the popover:

<input type="text" ng-model="dynamicPopover.title" class="form-control exclude">

So, there are some tweaks and gotchas, but I'll leave that to you:

  1. You should set a default exclude class in the link function of the popover-close directive, in case one is not defined.
  2. You need to be aware that the popover-close directive is element bound, so if you remove the styles I set on the html and body elements to give them 100% height, you could have 'dead areas' within your viewport if your content doesn't fill it.

Tested in Chrome, Firefox and Safari.

jme11
  • 17,134
  • 2
  • 38
  • 48
  • WOW, this is very comprehensive. Thank you for this. I have a LOT of buttons on my page, so it kind of sucks to have to hide the popover (click on the backdrop) before I can interact with any other elements on the page. Is there anyway to avoid the backdrop? The UX would be a whole lot nicer to just hide on a mouse click anywhere but the popover. Regardless though, this is a helluva answer and I REALLY appreciate it man! Thank you! – bryan May 29 '15 at 15:57
  • 1
    Totally valid point. Yeah, I can tweak this so that you can add the popoverBackdrop to the body tag. Give me a few minutes and I will update. – jme11 May 29 '15 at 17:13
  • This seems to want to run on ANY link on my site. And I keep getting a random error that `Error: undefined is not an object (evaluating 'angular.element(trigger[0]).triggerHandler('click').removeClass')`. Not sure why – bryan Jun 15 '15 at 15:18
  • 2
    I had to change my code to [this](http://pastebin.com/nR7XXfMa) because of dynamic loading of the popovers I'm assuming. But this ended up working. Thank you @jme11 – bryan Jun 15 '15 at 19:42
  • do you have any suggestions on getting this to work with 2 popovers? It keeps glitching up on me and I can't figure out how to get it to work. – bryan Jun 16 '15 at 00:57
  • Any chance you can reproduce the problem in a Fiddle or Plunker? – jme11 Jun 16 '15 at 09:11
  • [here you go](http://plnkr.co/edit/SUPfPbBhkFjG8n54wpcD?p=preview). When opening both up and closing them using the button, sometimes when I click on the body they re-appear because they aren't being "correctly" closed or something. – bryan Jun 16 '15 at 14:14
  • Okay, I'm not getting that error. But, to address the multiple buttons issue, it's simply a matter of looping through the triggers. I should have changed that when I changed the code anyway. Will update the answer, but you'll have to test because of the error thing. – jme11 Jun 16 '15 at 17:23
  • Yea I wasn't receiving the error in the plnkr just in my own code. But that would be awesome man if you could help me with the multiple buttons issue. I really appreciate it. – bryan Jun 16 '15 at 17:27
  • I don't see `i` being used in `closeTrigger(i)`. Is that supposed to do something? Because I'm loading content dynamically, I'm getting the same error I had. So I'll have to do some tests. Thanks for the update I'll let you know if I can figure it out – bryan Jun 16 '15 at 18:11
  • [Here](http://pastebin.com/T5AHtaju) are the changes I made and it works great! Thank you! I ended up having to separate `triggerHandler('click')` and `removeClass('popovr-trigger')` to be separate actions or else I would get that error for some reason. Also had to use jQuery to get the elements because of the dynamic loading. For some reason I had to move the `var trigger` to be declared and sent through the function because it wasn't getting any of my elements. – bryan Jun 16 '15 at 18:18
  • Glad you were able to make it work for your specific implementation! – jme11 Jun 16 '15 at 18:22
  • doesnt work with ui-bootstrap-tpls-0.13.4.js http://plnkr.co/edit/bMZeNenmvpZ4hs0pmnGy?p=preview – Jack Malkovich Sep 16 '15 at 10:46
  • 1
    Just a note for folks reading this chain. We've added a new feature in 0.14.0 that lets you programmatically open/close both tooltips and popovers. See my answer in this SO item for the same. @JackMalkovich – icfantv Sep 28 '15 at 18:00
  • 1
    When you click the button to open and then again you click the button to close the popover, clicking anywhere else after that will open the popover. In this [Plunk](http://plnkr.co/edit/72GLOK) i've provided a simple fix, the only change is `(element.hasClass('trigger'))? element.removeClass('trigger'): element.addClass('trigger');` in the `popoverDirective` – maljukan Nov 26 '15 at 23:13
  • This is not working for me pakprivatetutors.com/staging in the website i have hooked the concept for Ask Question Button in header –  Dec 31 '15 at 06:52
  • @Niyaz, please see my comments elsewhere in this article - we've added this feature in UIBS which is currently at 1.1.0. – icfantv Jan 22 '16 at 21:08
16

popover-trigger="'outsideClick'" This will work perfectly.

popover-trigger="outsideClick" This will not.

I took 1 day to sort it out why it was not working for me.

It is because they checking this using this code, "if (trigger === 'outsideClick')"

This is due to strong type check where we need to pass it as String

ajin
  • 1,136
  • 1
  • 11
  • 22
  • This "gotcha" had me... I was assuming a mystery event handler was eating the event before it could propagate. Added the single quote and works – Ezra Bailey Jul 18 '17 at 20:13
13

There is a property called popover-trigger that you can assign the property focus to.

<button 
      popover-placement="right" 
      popover="On the Right!" 
      popover-trigger="focus" 
      class="btn btn-default">
   Right
</button>

This does the trick! :)

Edit: To allow for the tooltip to be clicked on and not trigger focus lost, consider an approach similar to this

If you want it to work in angular, try creating your own trigger definition. Suggestions on how to do that can be found here.

Community
  • 1
  • 1
Patrick Motard
  • 2,650
  • 2
  • 14
  • 23
  • It is what I want, but it doesn't seem to work in the browser I'm using (latest Safari OS X). Focus seems to only work cross browser on `input` text – bryan May 28 '15 at 19:01
  • I have a browserStack account. Let me try it out in Safari OS X (Yosemite?) to confirm. – Patrick Motard May 28 '15 at 19:01
  • I'd appreciate that, yes Yosemite. I heard firefox also has this issue. – bryan May 28 '15 at 19:05
  • Yes there was a ticket submitted regarding this issue in both firefox and safari. I'm looking for a fix. The fix noted in the closed ticket is related to it not working if you don't include class="btn" which isnt the case for us. – Patrick Motard May 28 '15 at 19:08
  • Using `tabindex="0"` fixes it. However, in my popover, I have html with an `ng-click` which is ignored when using *focus* trigger. :( – bryan May 28 '15 at 19:11
  • Yes to add to your comment @bryan, the following works as far as getting a popup to show, but it will not hide on lose focus: – Patrick Motard May 28 '15 at 19:15
  • Yea @PatrickMotard I need an unconventional approach to hiding the popover since my popover content that needs to be actionable (i.e., links) – bryan May 28 '15 at 19:17
  • See edit in original solution. Let me know if it works for you. – Patrick Motard May 28 '15 at 19:23
  • If you look in the previous comments, `tabindex="0"` does fix it. But please look at the bottom of my original question that explains why I need to create an unconventional approach to my problem. – bryan May 28 '15 at 19:27
  • Ah... In that case you can create an event that closes sets a bool in scope equal to false when anything other than the tooltip element is clicked on. Then assign that bool to be the flag that the tooltip watches to determine whether or not it's visible. I can look into that further if you would like help. – Patrick Motard May 28 '15 at 19:31
  • 1
    That's the kind of approach I am looking for, but `.popover('hide')` does not work with angular bootstrap – bryan May 28 '15 at 19:41
8

What you are looking for is

<button
      popover-trigger="outsideClick" 
      class="btn btn-default">
   Right
</button>

From the documentation - The outsideClick trigger will cause the popover to toggle on click, and hide when anything else is clicked.

5

You can use:

Markup

<div ng-app="Module">
    <div ng-controller="formController">
        <button uib-popover-template="dynamicPopover.templateUrl" popover-trigger="focus" 
          popover-placement="left" type="button" class="btn btn-default">
             Popover With Template
        </button>

        <script type="text/ng-template" id="myPopoverTemplate.html">
            <div>
                <span>prasad!!</span>
            </div>
        </script>
    </div>
</div>

Javascript

<script type="text/javascript">
    var app = angular.module("Module", ['ui.bootstrap']);
    app.controller("formController", ['$scope', function($scope) {
        $scope.dynamicPopover = {
            templateUrl: 'myPopoverTemplate.html'
        };
    }]);
</script>
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
Prasad Shigwan
  • 520
  • 5
  • 14
3

I had the same issue and popover-trigger="'outsideClick'" worked for me. Interesting that the documentation did not state this issue.

svarog
  • 9,477
  • 4
  • 61
  • 77
Jake Scott
  • 31
  • 2
2

What about the 'outsideClick' option in the '$uibTooltipProvider' setTriggers method. Documentation says "The outsideClick trigger will cause the tooltip to toggle on click, and hide when anything else is clicked." Documentation

1

Angular boostrap ui new version 1.x having facility to out side click function. upgrade it to new version.

<button uib-popover-template="updatePassword.templateUrl" popover-title="Update Password" popover-trigger="outsideClick" popover-placement="right" popover-append-to-body="true">Click here</button>

its work for me.

focus will not work if any submit button or click event in popover. so this useful way to do.

Avinash Dalvi
  • 8,551
  • 7
  • 27
  • 53
0

Add onclick="void(0)" behavior to some of your background elements which when tapped will get rid of the popovers.

Have a look at https://github.com/angular-ui/bootstrap/issues/2123

npn
  • 103
  • 1
  • 12
0

1) Use ng-bootstrap for Popover.

2) Update the ng-bootstrap version to 3.0.0 or above. i.e npm install --save @ng-bootstrap/ng-bootstrap@3.0.0

3) After updating, you may use [autoClose] functionality of Ngbpopover.

<button type="button" class="btn btn-outline-secondary" popoverTitle="Pop title" [autoClose]="true" ngbPopover="Click anywhere or press Escape to close (try the toggling element too)">Click to toggle</button>

4) Hope it helps !