Search code examples
javascriptjqueryhtmltwitter-bootstrappopover

how to dismiss bootstrap popover when either click again or click elsewhere


I can use data-trigger='focus' to dismiss a popover when click outside, or data-trigger='click' when click the button again. But I can't have BOTH. That is, if I use focus, clicking the popover button won't do anything.

I'd like to dismiss popover in either case, does anyone know a way to do this easily?

I tried data-trigger='focus click', but it doesn't work.

EDIT: I don't think this is a duplicated question. Sure the solution in that question work for me. But the title of that question: "How to dismiss a Twitter Bootstrap popover by clicking outside" is misleading. If I just want dismiss the popover by clicking outside, I just need data-trigger='focus', as said by bootstrap document:

Use the focus trigger to dismiss popovers on the next click that the user makes.

But as I explained, it won't work if you click the popover trigger again.


Solution

  • I'm not to sure what you mean without seeing any code but I would do it using jQuery:

        $('body').on('click', function (e) {
    
        if ($(e.target).data('toggle') !== 'popover'
            && $(e.target).parents('.popover.in').length === 0) { 
            $('[data-toggle="popover"]').popover('hide');
        }
    });
    

    I hope I was of some help, good luck!