This is an improvement of @Gökhan Kurt answer.
His solution places the tooltip to the left or right of the multiline link. However, I wanted to improve this and make it look better. So, when you hover the upper line, the tooltip appears on the left side of the link; and when you hover the bottom line, the tooltip appears on the right side of the link.
For that, I detect where the user hovers the link. If it it's near the right side of the window, it means it's the upper line. Otherwise, it's the bottom line. This works if you set the container: 'body'
in the tooltip options.
For Bootstrap v3.3.6, tooltip plugin source code:
Get the mouse position in the enter
function:
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
var mousePos = { x: -1, y: -1 };
mousePos.x = obj.pageX;
mousePos.y = obj.pageY;
window.mousePos = mousePos;
}
In the show
function clear the placement CSS class (because it may be different each time you hover the link) and set the new placement depending on the mouse position:
var isTextPlacement = /textleft|textright/.test(placement)
if(isTextPlacement){
$tip.removeClass("textright");
$tip.removeClass("textleft");
}
//390 is hardcoded value which is the max size of the tooltip, you may adjust to your case
if(placement == 'textleft' && window.mousePos.x < 390){
placement = 'textright';
}else if(placement == 'textright' && window.mousePos.x > $(window).width() - 390){
placement = 'textleft';
}
For the getCalculatedOffset
, I used the following, which applies textleft
if textright
can't be applied.
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
var windowWidth = $(window).width();
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement=='left'?{ top: pos.top+pos.height/2-actualHeight/2, left: pos.left-actualWidth }:
placement == 'right' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } :
placement=='textleft' && window.mousePos.x > 390 ? { top: pos.firstRect.top+(pos.firstRect.height/2)-actualHeight/2, left: pos.firstRect.left-actualWidth }:
/*placement=='textright'*/ window.mousePos.x < windowWidth - 390 ? { top: pos.lastRect.top+(pos.lastRect.height/2)-actualHeight/2, left: pos.lastRect.right }:
/*apply textleft*/ { top: pos.firstRect.top+(pos.firstRect.height/2)-actualHeight/2, left: pos.firstRect.left-actualWidth }
}
And that's it. Check the JSFiddle (Resize the output window in order to make the links span over two lines and compare with @Gökhan Kurt answer. You might need to set it bigger, because of the hardcoded 390px).