Search code examples
javascripthtmlcsslaravel-bladepopover

How to make clickable popover disappear if I clicked outside of it


I have this popover contain some info and URL to another page so when I clicked on it it's open, but when I click outside of it it won't disappear,

`<i class="bi bi-question-circle text-primary float-right" data-bs-toggle="popover" data-bs-content="{{$accountTypeQuestionMark[$value] ? $accountTypeQuestionMark[$value]:''}}" data-bs-trigger="click"  data-bs-html="true" ></i>
`

and this the JavaScript for it:

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
        var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl)
    })
</script>

I tried using this code but it didn't work:

$(document).on('click', function (e) {
    $('[data-bs-toggle="popover"]').each(function () {
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            $(this).popover('hide');
        }
    });
});```

Solution

  • You are gonna have to make these changes in your popover for this functionality: tabindex="0" and change data-bs-trigger to focus. And in the end, it will look like this:

    <i class="bi bi-question-circle text-primary float-right" tabindex="0" data-bs-toggle="popover" data-bs-content="{{$accountTypeQuestionMark[$value] ? $accountTypeQuestionMark[$value]:''}}" data-bs-trigger="focus"  data-bs-html="true" >Click here for popover</i>
    

    var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
        var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl)
    })
    <!DOCTYPE html>
    <i class="bi bi-question-circle text-primary float-right" tabindex="0" data-bs-toggle="popover" data-bs-content="{{$accountTypeQuestionMark[$value] ? $accountTypeQuestionMark[$value]:''}}" data-bs-trigger="focus"  data-bs-html="true" >Click here for popover</i>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js"></script>