Popover Reposition
by Hayriye Aydin
HTML
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<button id="popover">
Popover
</button>
CSS
button {
position: absolute;
top:50%;
left: 50%;
}
JavaScript
$(function () {
$.fn.popover.Constructor.prototype.reposition = function () {
var $tip = this.tip()
var placement = typeof this.options.placement === 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
var orgPlacement = placement
var viewportDim = this.getPosition(this.$viewport)
placement = placement === 'bottom' &&
pos.bottom + actualHeight > viewportDim.bottom ? 'top' : placement === 'top' &&
pos.top - actualHeight < viewportDim.top ? 'bottom' : placement === 'right' &&
pos.right + actualWidth > viewportDim.width ? 'left' : placement === 'left' &&
pos.left - actualWidth < viewportDim.left ? 'right' : placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
}
// Initialize Popover with minimal Content
$('#popover').popover({
title: 'Reposition',
content: 'No Content',
placement: 'top'
})
// Dyanmically change the popover content and reposition it
$('#popover').on('shown.bs.popover', function () {
setTimeout(function () {
$('.popover-content').html('New content<br/>Inserted dyanmically<hr/>Repositioned<br/> :\)')
$('#popover').popover('reposition')
}, 1000)
})
})