jQuery UI Autocomplete Width Not Set Correctly jQuery UI Autocomplete Width Not Set Correctly jquery jquery

jQuery UI Autocomplete Width Not Set Correctly


I use this drop-in solution:

jQuery.ui.autocomplete.prototype._resizeMenu = function () {  var ul = this.menu.element;  ul.outerWidth(this.element.outerWidth());}

That's basically @madcapnmckay's solution, but that doesn't need to change the original source.


It turns out the problem is that the menu is expanding to fill the width of its parent element, which by default is the body. This can be corrected by giving it a containing element of the correct width.

First I added a <div> like so:

<div id="menu-container" style="position:absolute; width: 500px;"></div>

The absolute positioning allows me to place the <div> immediately after the input without interrupting the document flow.

Then, when I invoke the autocomplete, I specify an appendTo argument in the options, causing the menu to be appended to my <div>, and thus inherit its width:

$('#myInput').autocomplete({ source: {...}, appendTo: '#menu-container'});

This fixes the problem. However, I'd still be interested to know why this is necessary, rather than the plug-in working correctly.


I had a dig around in the autocomplete code and the culprit is this little blighter

_resizeMenu: function() {    var ul = this.menu.element;    ul.outerWidth( Math.max(        ul.width( "" ).outerWidth(),        this.element.outerWidth()    ) );},

I'm not sure what ul.width("") is suppose to be doing but ui.width("").outWidth() always returns the width of the body because that's what the ul is appended to. Hence the width is never set to the elements width....

Anyway. To fix simply add this to your code

$element.data("autocomplete")._resizeMenu = function () {        var ul = this.menu.element;        ul.outerWidth(this.element.outerWidth());}

Is this a bug?

EDIT: In case anyone wants to see a reduced test case for the bug here it is.