1

I have made a simple tooltip generator using JQuery 1.10.2 that reads the element's title value.

It's working okay, apart from if the element is to the right of the screen, sometimes the tooltip floats off the edge of the page.

If the element is near the right of the page, I'd like to positioning it somewhere close to the right-edge of the element.

My code is below, and also a JSFiddle. All input appreciated!

function BuildTipsV3() {
    var tt = $("#ttfloat");
    $("[title]").on({
        mouseenter: function() {
            // set tooltip
            var o = $(this).offset();
            var y = o.top;
            var x = o.left;
            var tooltip = $(this).attr('title') || $(this).data('title');
            $(this).attr('title', '');
            $(this).data('title', tooltip);
            tooltip = tooltip.replace(/(\r\n|\n|\r)/gm, "<br/>");
            tt.html(tooltip);
            // position tooltip and show
            var ttRightSide = x + tt.width();
            if (ttRightSide < $(window).width()) { 
                tt.css({ top: (y + 15), left: (x + 5) });
            } else { 
                tt.css({ top: y, right: 0 }); // <-- problem (right:0) doesn't work
            }
            tt.show();
        },
        mouseleave: function () {
            $("#ttfloat").hide();
            $(this).attr('title', $(this).data('title')); // reset for accessibility
        }
    });
}

http://jsfiddle.net/HSfHD/2/

3 Answers 3

1

You were so close.

FIDDLE

You just need to reset the left and right styles when you're not using them:

if (ttRightSide < $(window).width()) {
    tt.css({
        top: (y + 15),
        left: (x + 5),
        right:'auto'
    });
} else {
    tt.css({
        top: y + 15,
        right: 0,
        left:'auto'
    });
}
0
1

If you hover on the left element it sets the CSS left but when you hover on the right element you only set the CSS right property, so the final style will have both left and right set.

You need to reset the left back to its default value first (and probably the same for the other properties), for example see demo where I have added the following code:

if (ttRightSide < $(window).width()) {
    tt.css({
        top: (y + 15),
        right: 'auto',
        left: (x + 5)
    });
} else {
    tt.css({
        top: y + 15,
        right: 0,
        left: 'auto'
    });
}
0
0

Just calculate the left instead.

tt.css({
    top: y+20,
    left: $(window).width() - tt.width() - 20
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.