Fabrizio Mazzoni
Fabrizio Mazzoni

Reputation: 1909

jquery autocomplete not sticking to the element from which its called

I have a div inside my webpage that is set as draggable with jquery. Inside it I load a webpage with the .load() function and there are textboxes which use the jquery autocomplete function.

The moment I start typing and the dropdown appears, if I drag the div to move it on a side, the dropdown will remain in the same position but the div moves.

Is there any option to force the dropdown to bind itself to the textbox so that if the div is moved the dropdown will follow?

Upvotes: 0

Views: 1016

Answers (1)

rd3n
rd3n

Reputation: 4560

As explained you must either:

  1. Adjust the autocomplete menu position while dragging your div
  2. Or close the autocomplete when dragging start

1. Adjust the autocomplete menu position while dragging

This can be easily done by calling jquery-ui .position() while dragging :

$( "#drag" ).draggable({
    drag: function(e, ui) {
        $('.ui-autocomplete.ui-menu').position({
            my: 'left top',
            at: 'left bottom',
            of: '#tbox'
        });
    }
});

jsFiddle

  • +: search results stay visible and you don't have to perform search again (or at least redisplay results) when dragging stop
  • -: many calls to jquery-ui position because the drag event will be raised many times. Plus your user have to click outside your draggable div to close the autocomplete menu

2. Close the autocomplete when dragging start

As you click on your div to drag, it is quite common to unfocus the input (common behaviour when you click outside an input). So just perform this when dragging start :

$( "#drag" )
    .draggable({
        start: function(e, ui) {
            // unfocus input will close the autocomplete menu
            // you can also call $( "#tbox" ).autocomplete('close');
            // but your input will still have focus and you will
            // need to use the down arrow key to redisplay autocomplete results
            // or perform another keypress
            $( "#tbox" ).blur();
        }
    });

jsFiddle

  • +: just one .blur() when dragging start. Common behaviour for end user
  • -: user have to select the input again and press a key (like down arrow key) to display results. Another search has to be done (can be annoying if you use remote data for your autocomplete field)

Another solution would be to use the 2nd scenario and to add a listener to the stop draggable event, in which you redisplay results (if there are results)

Upvotes: 2

Related Questions