Thursday, March 10, 2016

Keeping the Bootstrap Popover alive while mouse moves from triggering element to the popover

I tried to use the Bootstrap Popover as a quick dynamic ajax form within which I can perform further actions. By default, when popover appears as a result of hovering over the triggering element, it disappears when the triggering element is no longer hovered.

One easy way to keep the popover stay put until I am no longer hovering over the triggering element or the popover itself is to use { trigger: "manual", html: true, animation: false } and handle the trigger via "mouseenter" and "mouseleave" event.

// the triggering element has class of 'pop'
$(".pop").popover({
    trigger: "manual", 
    html: true,
    animation: false
}).on("mouseenter", function(){
    var _this = this;
    $(this).popover("show");
    $(".popover").on("mouseleave", function(){
      $(_this).popover('hide');
    });
}).on("mouseleave", function(){
    var _this = this;
    setTimeout(function(){
      if (!$(".popover:hover").length){
        $(_this).popover("hide");
      }
    }, 50); 
    // If popover is not hovered within 50 milliseconds 
    // after the mouse leaves the triggering element, 
    // the popover will be hidden. 
    // 50 milliseconds seem fine in most cases.
});

No comments: