Bootstrap data placement based on window width

I'm looking for an easy 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 doesn't change when I resize the window. 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 page width and hit the popover button again. Data placement does not change. Suggestions? Thanks in advance!

+3


source to share


1 answer


Duplicate of this question answered by bchhun

Go to 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 that it works. Hope this helps!

+3


source







All Articles