Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get width of tooltip and calculate placement (Twitter Bootstrap)

This is a follow up to my previous question.

I need to place Bootstrap tooltips dynamically. To do so, I need to know the position of the element which triggers the tooltip (works fine) AND the width of the tooltip which is supposed to show up:

Edit for clarification: My tooltips are generated dynamically and then inserted into the content. If they are, for example, too close to the left edge of the screen I need to place them 'right' instead of 'top'. Now I want to get the width of the tooltip to only place it 'right' when it would actually go out of the screen.

$('body').tooltip({
    delay: { show: 300, hide: 0 },
    selector: '[rel=tooltip]:not([disabled])',
    placement: function(tip, element) {
        var offsetLeft = $(element).offset().left;
        var offsetRight = ( $(window).width() - ( offsetLeft + $(element).outerWidth() ) );

        // need help here: how to get the width of the current tooltip?
        // currently returns "0" for all elements
        var tooltipWidth = $(tip).outerWidth();
        console.log(tooltipWidth);

        if (offsetLeft < 220) {
            return 'right';
        }
        if (offsetRight < 220) {
            return 'left';
        }
        else {
            return 'top';
        }
    }
});

Thanks in advance.

like image 454
maze Avatar asked Oct 31 '25 17:10

maze


1 Answers

From a logically point of view it is impossible :) Think about it - the tooltip calls the placement function to get its position, and then it inserts the tip to the page and style it.

However, you can create a dummy-tip with the same features as the soon-to-come tip, and by that get the width. Like this :

$('body').tooltip({
    delay: { show: 300, hide: 0 },
    placement: function(a, element) {

        //title is by tooltip moved to data-original-title
        var title=$(element).attr('data-original-title');

        //create dummy, a div with the same features as the tooltïp
        var dummy=$('<div class="tooltip">'+title+'</div>').appendTo('body');
        var width=$(dummy).width();
        dummy.remove();

        //now you have width 
        //..
        //..

        var position = $(element).position();
        if (position.left > 515) {
            return "left";
        }
        if (position.left < 515) {
            return "right";
        }
        if (position.top < 110){
            return "bottom";
        }
        return "top";
    },
    selector: '[rel=tooltip]:not([disabled])'
});
like image 94
davidkonrad Avatar answered Nov 03 '25 09:11

davidkonrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!