Search code examples
jquerytwitter-bootstrap-3popover

Bootstrap popover to appear on hover and remain for a second


I would like a popover to appear on hover, but to remain only if the user is interacting with it (it contains links) if not, it should disappear after 500ms.

Javascript

$(document).ready(function(){
    $('[data-toggle="tooltip"]').popover({ title: 'Look! A bird!', html:true, delay: { show: 100, hide: 1000 } });
});

PHP

<button type="button" class="badge btn btn-default" data-trigger="click" data-toggle="tooltip" data-placement="top" data-html=true data-content="@foreach($tag->tracks as $track) <a href='/tracks/{{ $track->mdbid }}'>{{ $track->title }}</a> @endforeach">{{ $tag->tracks->count() }}</button>

Ignore the funny code inside the brackets (It is Laravel blade syntax)

JSFiddle

I have created this JSFiddle although it doesn't work properly (it does on my machine). I have got the delay working. However, if the mouse is within the popover, it still disappears. How can I prevent this and make it only disappear when the mouse it outside the popover?


Solution

  • THIS IS NOT MY WORK, I DO NOT KNOW WHO THE ORIGINAL AUTHOR IS BUT ALL CREDIT GOES TO THEM

    This JSFiddle solved it.

    HTML

    <p id='container'>
    <button class='btn btn-primary btn-large' data-popover="true" data-html=true data-content="<a href='http://www.wojt.eu' target='blank' >click me, I'll try not to disappear</a>">hover here</button>
    </p>
    

    Javascript

    var originalLeave = $.fn.popover.Constructor.prototype.leave;
    $.fn.popover.Constructor.prototype.leave = function(obj){
      var self = obj instanceof this.constructor ?
        obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
      var container, timeout;
    
      originalLeave.call(this, obj);
    
      if(obj.currentTarget) {
        container = $(obj.currentTarget).siblings('.popover')
        timeout = self.timeout;
        container.one('mouseenter', function(){
          //We entered the actual popover – call off the dogs
          clearTimeout(timeout);
          //Let's monitor popover content instead
          container.one('mouseleave', function(){
            $.fn.popover.Constructor.prototype.leave.call(self, self);
          });
        })
      }
    };
    
    
    $('body').popover({ selector: '[data-popover]', trigger: 'click hover', placement: 'auto', delay: {show: 50, hide: 400}});
    

    CSS

    #container {
        text-align: center;
        margin: 8em 3em;
    }