3

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!

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
jbertog
  • 33
  • 6
  • It works fine here. [jsFiddle](https://jsfiddle.net/greenfoxx/LnqL7L6o/) What version of `bootstrap` and `jquery` are you using? – jofftiquez May 16 '15 at 07:15
  • Didn't seem to work when I went to your fiddle. The glyph icon works fine when adjusting window size. When I load a full screen page and click on the popover, it places the content where it should be. Then, when I resize the window and click again, everything works except the jquery line that changes the data-placement attribute. strange.. – jbertog May 16 '15 at 07:55

1 Answers1

3

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!

Community
  • 1
  • 1
Pred
  • 676
  • 1
  • 7
  • 14