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
}
});
}