How to break line in jQueryUI tooltip

woraphol.j picture woraphol.j · Oct 25, 2012 · Viewed 41.5k times · Source

The new version of jQueryUI (1.9) comes with the native tooltip widget. After testing with it, it works fine if the content (value of the title attribute) is short. But if the content is long, the tooltip, once displayed, will overlap the input text.

There is a demo on the official site.

When you hover the mouse cursor over the Your age text <input>, the tooltip displayed overlaps the text input. I am not sure if this is the desired behaviour of the widget. I would like it to stay on the right side of the text input and break lines if necessary.

Edit: The demo page no longer shows the original problem since the demo has been updated to use jQueryUI v1.10 in which the position code was updated to better place the tooltip - see http://api.jqueryui.com/tooltip/#option-position

I have re-created a demo of the original problem on jsFiddle.

Answer

andyb picture andyb · Oct 25, 2012

The placement of the tooltip is controlled by a jQueryUI Position object and the default settings are:

{ my: "left+15 center", at: "right center", collision: "flipfit" }

The Position Object, in particular the collision attribute can be changed to force placement of the control somewhere else. The default for tooltips is flipfit which means the if the default (on the right) does not fit it will flip to the left and try that position and if that doesn't collide with anything, try to fit the control by moving it away from the edge of the window. The result is that it now collides with the <input>. There doesn't seem to be an option to force a long tooltip to cleverly wrap.

However there are two ways to wrap the content:

Add a custom CSS class to the configuration with a max-width to force wrapping, for example:

JavaScript

$('input').tooltip({
    tooltipClass:'tooltip'
});

CSS

.tooltip {
    max-width:256px;
}

Or insert hard line-breaks <br/> in the title attribute, for example

title="Lorem ipsum dolor sit amet,<br/>consectetur adipisicing elit"

Edit: So it looks like jQueryUI changed the tooltip content option between v1.9 and v1.10 (according to the changelog). For reference here is the difference:

v1.9.2

content: function() {
    return $( this ).attr( "title" );
}

v1.10

content: function() {
    // support: IE<9, Opera in jQuery <1.7
    // .text() can't accept undefined, so coerce to a string
    var title = $( this ).attr( "title" ) || "";
    // Escape title, since we're going from an attribute to raw HTML
    return $( "<a>" ).text( title ).html();
}

So you can put back the older functionality that does not escape <br/> tags in the title attribute by using the .tooltip() like this:

$('input').tooltip({
    content: function() {
        return $(this).attr('title');
    }
});

Also, see jsFiddle demo.