I am looking for a simple way to change my data-placement attribute based on window width for my popover in bootstrap. Below is my current html and jquery code. It works, but the data-placement for my popover does not change as I adjust the window size. Only if I refresh the page with a small window size does it actually work.
<a class="arrow" id="arrow" data-toggle="popover" data-content=""><span class="glyphicon glyphicon-menu-right" id="glyph"></span></a>
<script>
$(window).resize(function(){
console.log('resize called');
var width = $(window).width();
console.log(width);
if(width < 974){
$('#glyph').removeClass('glyphicon-menu-right').addClass('glyphicon-menu-down');
$('#arrow').attr('data-placement','bottom');
$('.myInfo').css("margin-top", "10px");
$('.myInfo').css("margin-left", "30px");
}
else if(width > 974){
$('#glyph').removeClass('glyphicon-menu-down').addClass('glyphicon-menu-right');
$('#arrow').attr('data-placement','right');
$('.myInfo').css("margin-top", "60px");
$('.myInfo').css("margin-left", "40px");
}
})
.resize();
</script>
Everything works except when I change the width of page and click on the popover button again. The data-placement does not change. Suggestions? Thanks in advance!
Duplicate of this question answered by bchhun
Pass in the placement position as a function:
var options = {
placement: function (context, source) {
if ($(window).width() < 974) {
return "bottom";
} else {
return "right";
}
}
};
$("[data-toggle=popover]").popover(options);
$(window).resize(function(){
var width = $(window).width();
if(width < 974){
$('#glyph').removeClass('glyphicon-menu-right').addClass('glyphicon-menu-down');
$('.myInfo').css("margin-top", "10px");
$('.myInfo').css("margin-left", "30px");
}
else if(width > 974){
$('#glyph').removeClass('glyphicon-menu-down').addClass('glyphicon-menu-right');
$('.myInfo').css("margin-top", "60px");
$('.myInfo').css("margin-left", "40px");
}
})
.resize();
This Bootply shows it working. Hope this helps!