Search code examples
jquerytwitter-bootstrappopover

PopOver auto adjust placement


I am facing an issue with PopOver. I want it to auto adjust at all positions. If it doesn't find space on right side it opens at left. But I want it to do the same thing for top/bottom. i.e if it doesn't find space at top it should open at bottom and vice versa. Isn't there any way I can do it for all sides?

$('[data-toggle="popover"]').popover({
        trigger: 'manual',
        placement: 'auto right'
    })

The HTML

<a data-toggle="popover" class="hlpicon" data-html="true" data-trigger="hover" data-container="body" data-content="This will open a popover" data-original-title="" title=""></a>

Solution

  • You should be able to use the placement option as either a string or a function returning a string:

    $('[data-toggle="popover"]').popover({
        trigger: 'manual',
        placement: function (context, source) {
            var position = $(source).position();
    
            if (position.left > 515) {
                return "left";
            }
    
            if (position.left < 515) {
                return "right";
            }
    
            if (position.top < 110){
                return "bottom";
            }
    
            return "top";
        }
    });
    

    For context, the source of this code is Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge? (which declares attribution to be not required - just adding this as a resource).