cdub
cdub

Reputation: 25701

Clicking on a link in a Bootstrap popover

I am using Bootstrap js popovers to show an html list with links. But I am having trouble grabbing the links when they are clicked with a jquery selector:

The element for the popover:

<span class="popoverSpan" data-style="listPopovers" data-html="true" data-container="body" data-placement="bottom" data-trigger="focus" data-toggle="popover" tabindex="0" data-original-title="" title="">Menu</span>

<div>
    <ul id="forPopover" class="dropdown-menu popover-content">
        <li id="List_3" class="subgroups">
            <a id="aInner">Students</a>
        </li>
        <li id="" class="subgroups">
            <a id="bInner">Teachers</a>   
        </li>
    </ul>
</div>



$(".popoverSpan").popover({
        html: true,
        content: function () {

            return $('#forPopover').html();
        }
    });


 $('body').on('click', '.subgroups a', function (event) {
       alert('a');
    });

I have the popover html above and the JQuery and bootstrap code below it. The alert('a') is intermittent. Why is this the case and how do I fix it? Thanks.

Upvotes: 1

Views: 3045

Answers (1)

jim
jim

Reputation: 1053

It's a bit late for OP, but I just ran into this myself (I'm on Bootstrap v3.2). The problem is the data-trigger="focus".

If you look at the description in the docs focus is also described as "dismiss on next click", which it turns out includes clicks on the popover itself and even clicks on links in the popover. So there's a race between the click making bootstrap dismiss the popover and the click event reaching the link and actually open a new page.

Personally I think making focus dismiss on the next click anywhere but on the popover would be more intuitive.

Anyway, there are two solutions I can see. The first is to set the data-trigger to manual, then reimplement focus but don't dismiss if the click is on the popover.

The other is a bit more hacky, but if you add a delay, with data-delay="500" or preferably .popover(delay: {show: 0, hide: 500}), then the delay gives the click event time to open the page before the dismissal goes through. The latter only delays on close so since they'll be looking at a new page the delay isn't a problem if you don't want it. N.B. in theory you should also be able to do data-delay="{show: 0, hide: 500}" but I couldn't get that to work.

The second workaround is quick and easy, and the unwanted delay shouldn't be too big a deal, but be aware that there's always a chance of running into timing problems intermittently under certain conditions (faster/slower machine, diff browser, who knows?). So it could fail in CI or something. The higher you make the delay the smaller the chance that's a problem (e.g. I tried 50 and it virtually never worked for me) but then you've got a big delay to deal with.

Upvotes: 8

Related Questions