简体   繁体   中英

How to make simple autocomplete-like DIV that reacts on focus/blur events of input element?

I have this simple scenario (simplified for the sake of this question):

<input type="text" id="input">
<div id="autocomplete">.. some links..</div>

<script>
  $('#input').bind('focus', function(){
    $('#autocomplete').show();
  }).bind('blur', function(){
    $('#autocomplete').hide();
  });
</script>

What I want to achieve is this:

  1. When user clicks in text input, autocomplete appears.
  2. When user clicks on anything in autocomplete DIV, it stays visible
  3. When user clicks anywhere outside of input and autocomplete then autocomplete disappears.

How can I achieve this ? Especially I am looking for an answer on the second point, because it must be easily achievable.

Thank you for your help in advance.

Correct me if I'm wrong, but I believe your code works for requirements #1 and #3, but not #2:

When user clicks on anything in autocomplete DIV, it stays visible

That's because clicking on the div will cause the input field to lose focus, so the blur code would hide the div immediately. This means you can't use the blur event for hiding the div. You could bind to click on document . From within the handler you'll have to check if you should hide the div or not:

$(document).click(function(e){
    var inputFocused = $('#input').is(':focus');
    var clickedInsideAcDiv = $(e.target).closest('#autocomplete').length > 0;
    if(!inputFocused && !clickedInsideAcDiv) {
        $('#autocomplete').hide();
    }
});

I'm not sure if this will account for everything on your actual page, but I hope the idea is clear.

I know it's cool to hack everything together on your own, but you might want to look at this jQuery autocomplete plugin: http://jqueryui.com/demos/autocomplete/

UPDATE

<script>
  $('#input').bind('focus', function() {
    $('#autocomplete').position($(this).position()); //Adjust this accordingly depending on where you want the autocomplete div to show up.
    $('#autocomplete').show();
  }).bind('blur', function(){
    $('#autocomplete').hide();
  });
</script>

CSS:

<PARENT_OF_#autocomplete> {
    position: relative; /* Anything other than static or default one */
} 

#autocomplete {
    position: absolute;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM