juju
juju

Reputation: 994

How can I fade popover() automatically by targeting inner html button tag "data-content"

I don't know much of anything about Javascript, but I have a popover() function that displays pop-up text when a button is clicked. I want just the popped up text to fade automatically, about 2 seconds after the button is clicked. They way I have this piece of code set up, it closes the actual button after 2 seconds instead of the pop-up box. I figure I need to target the data-content element somehow, but I am unsure how to. Your help would be much appreciated.

<script type="text/javascript">
    $(function () {
      $('[data-toggle="popover"]').popover()
    })

    setTimeout( function () {
        $('[data-content="item added"]').hide('fade')     
    }, 2000)

</script>

<button type="button" class="btn btn-lg btn-danger" data-toggle="popover" data-animation="true" title="Popover title" data-content="item added">Click to toggle popover</button>

Upvotes: 0

Views: 413

Answers (2)

Steve Mulvihill
Steve Mulvihill

Reputation: 717

Here is an approach that uses jQuery to create a new DOM element for your tooltip and uses .fadeOut() to remove it on click. You just need to add the .tooltip-trigger class to any element with a title attribute to get the same effect across your pages.

$('.tooltip-trigger').hover(function(){
  

var title = $(this).attr('title');
  $(this).data('tipText', title).removeAttr('title');
  $('<p class="tooltip"></p>')
         .text(title)
         .appendTo('body')
         .fadeIn('slow');
}, function() {
  $(this).attr('title', $(this).data('tipText'));
  $('.tooltip').remove();
});

$('.tooltip-trigger').mousemove(function(e) {
  var mouseX = e.pageX + 20; //Get X coords
  var mouseY = e.pageY + 10; //Get Y coords
  $('.tooltip').css({ top: mouseY, left: mouseX })
});

$('.tooltip-trigger').click(function(e) {
  $('.tooltip').fadeOut( "slow" );
});
.tooltip {
  display:none;
  position:absolute;
  background-color:#ffff94;
  border: 1px solid grey;
  border-radius:5px;
  padding:2px;
  font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button type="button" class="btn btn-lg btn-danger tooltip-trigger" title="Popover title">Click to toggle popover</button>

Here is a fiddle.

Upvotes: 1

MajiD
MajiD

Reputation: 2585

this should work. time is in milliseconds.

remove trigger line if you want the pop-over to show with click

$('[data-toggle="popover"]').popover({
    delay: { "show": 1000, "hide": 2000 },
    trigger: 'hover'
})

Upvotes: 1

Related Questions