In the snippet below, I have a Bootstrap Popover which supports both Hover & Click modes. On Click, the window stays open and should close either on (1) self-click (link again), or (2) any outside click.
PROBLEM: After an outside click, the popover goes to the “currently open” mode. This means that if you hover over it again, the window is stuck and won’t disappear. What should happen is, after an outside click, you revert to the original Hover-and-Disappear mode when you hover over it again. The same behavior is expected here as when hovering after an inside-close-click, which is the original state. Am I forgetting something?
$('#linkPopover').popover({
trigger: 'hover click',
content: 'This is my content',
title: 'TITLE'
});
// -----------------
// Just with the above (and no other code), the Hover and Click-Toggle
// works within the SAME Popover window,
// but now I need to also remove the visible Popover on ANY CLICK OUTSIDE.
// However, although the below works, *after* clicking outside the Popover is in the CLICKED
// mode i.e. it doesn't hover anymore
$('body').on('click', function(e) {
$('[data-toggle="popover"]').each(function () {
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
// From outside click with the popover open, need to hide
$(this).popover('hide');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<a id="linkPopover" data-toggle="popover">POPOVER</a>
<br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/>
End of body
3
Answers
I actually solved the infinite-loop in eminememinem's original answer (due to
trigger('click')
) by introducing a custom flag parameter in thebody.click
. You can do that asWe set the flag in the special case of our own re-triggering. If so we ignore the regular logic.
Full snippet:
This code might help you. I changed your conditional statements to check if the user is clicking outside of the popover trigger && if the popover is visible, then trigger the
click
event of the popover trigger.I thought of doing this because the
click
event is the event that occurs when you click the trigger itself.My first answer produces the
Maximum call stack size exceeded
error due to an infinite loop when there are more than 1 popover (see my first answer and comments).To solve this: I use
.off
on the body click handler whenever the system is about to execute thetrigger('click')
. After that I reinitialize the body click handler. See sample below.