Search code examples
javascripttwitter-bootstrappopover

Bootstrap3 popover data-trigger=focus closing popup when clicking on <select> input within popup


I am using a bootstrap popover and have a <select> field inside of the popover in order for the user to change languages.

If they click outside the popover, I want it to disappear, so I am using the data-trigger="focus" attribute within the <a> tag to accomplish this.

However, if they click on the <select> drop down menu, the popover disappears before they can click a language.

Below is a bootply for your reference - any help is much appreciated.

http://www.bootply.com/SEM4ophIhx

Javascript:

$(function () {
    $('[data-toggle="popover"]').popover()
})

$(function () {
    $('[rel="popover"]').popover({
        container: 'body',
        html: true,
        content: function () {
            var clone = $($(this).data('popover-content')).clone(true).removeClass('hide');
            return clone;
        }
    }).click(function (e) {
        e.preventDefault();
    });
});

HTML:

<a href="#" role="button" data-placement="right" data-trigger="focus" rel="popover" data-popover-content="#profilesettingsaction">
<span class="glyphicon glyphicon-cog"></span>
</a>
    <div id="profilesettingsaction" class="hide">                               
      <ul>
        <li>
          <select name="language">
            <option value="">العربية: الإمارات العربية المتحدة</option>
            <option value="">中国</option>
            <option value="">中國</option>
            <option value="">Nederlands: Nederland</option>
            <option value="">English: United Kingdom</option>
            <option value="" selected="">Language: English</option>
            <option value="">Français: France</option>
            <option value="">Italiano: l'Italia</option>
            <option value="">日本語:日本</option>
            <option value="">Português: Portugal</option>
            <option value="">Español: México</option>
          </select>
        </li>
      </ul>                                
    </div>

Solution

  • Found a way to do this

    $('[data-toggle="popover"]').popover();
    
    $('body').on('click', function (e) {
        $('[data-toggle="popover"]').each(function () {
            //the 'is' for buttons that trigger popups
            //the 'has' for icons within a button that triggers a popup
            if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
                $(this).popover('hide');
            }
        });
    });
    

    You simply catch click events on the body and check if the target is a child of your popover. However this is really slow.