JqueryUi Autocomplete shown in wrong place when using input field in div with position:fixed

JeanValjean picture JeanValjean · Sep 2, 2012 · Viewed 30k times · Source

I have a "modal window" in a webpage obtained by applying to a div the css property position to fixed. The div contains input fields. In particular, I'm using the autocomplete widget from jQueryUI. There are two major problems:

1) the first is that, since the div has a fixed position, when you scroll down the webpage, the autocomplete suggestions are not shown fixed but are moved up and down with the page. You can see that problem at this Codepen where I'm using an example from jQuery website with city-name autocompletion.

2) The second problem is that the suggestions from autocomplete are shown in the upper-left corner of the page and not just below the input field. Unfortunately, I tried to reproduce this problem in Codepen, but I can't.

I'm quite sure that the problem is due to the CSS, and in particular to such style properties provided by the JQuery-UI. Maybe the problem can be resolved by using the position option of the autocomplete widget.

What CSS property should I define and how?

PS: I use the theme provided at http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css.

Answer

JeanValjean picture JeanValjean · Sep 2, 2012

Looking at the jQuery UI library, I see that the <ul> element is used to show the suggestions. jQuery UI appends this element by default to the HTML document and not to the <div> (used as "modal window") of the text input.

However, the documentation shows that the option appendTo configures which element the autocomplete <ul> should be appended to. It uses jQuery's appendTo() function. http://jqueryui.com/demos/autocomplete/#option-appendTo

So, I included a div to contains the suggestions:

<input type="text" id="myInput" />
<div id="container">
</div>

And in the autocomplete() function I added the option:

appendTo: "#container"

Then I added the following CSS

#container {
    display: block; 
    position:relative
} 
.ui-autocomplete {
    position: absolute;
}

That's all!