I want to hide automatically the Bootstrap popovers after a few seconds. When the user hovers over a control, the popover must be displayed, but if the user doesn't move the mouse pointer, this popover must be hidden automatically after few seconds.
That is important because in a mobile phone or tablet when the user taps a control, the popover is displayed, and the focus remains on the same control while the user types something, with the popover hindering it.
You really should give it a try and post your code before asking for help. This works, though there may be a more efficient method:
$('.pop').popover().click(function () {
setTimeout(function () {
$('.pop').popover('hide');
}, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<span class="pop" data-original-title="My popover" data-content="Isn't it great?">Click me</span>
The accepted answer works just fine, but here's a more bootstrap approach:
Original answer
$('.pop').on('shown.bs.popover', function () {
var $pop = $(this);
setTimeout(function () {
$pop.popover('hide');
}, 2000);
});
Update from limplash
This answer misses one key information!! you have to add the trigger option while initializing popover .. {trigger:"manual"} .. otherwise the bootstraps attaches an onclick event to which causes the issue of two click required after first use .. following should is a proposed solution
$("#element").popover({ trigger:"manual" }).click(function() {
var pop = $(this);
pop.popover("show")
pop.on('shown.bs.popover',function() {
setTimeout(function() {
pop.popover("hide")}, 2200);
})
})
You could also add your own new data-attribute to your popovers as such:
$('[data-toggle="popover"][data-timeout]').on('shown.bs.popover', function() {
this_popover = $(this);
setTimeout(function () {
this_popover.popover('hide');
}, $(this).data("timeout"));
});
Now you could use
<span
data-toggle="popover"
data-timeout="2000"
title="A title"
data-content="Some explanatory text">
Your text
</span>
and the popover disappears after being shown the number of milliseconds you specified in data-timeout.
来源:https://stackoverflow.com/questions/14528442/auto-hide-bootstrap-popover