user3783952 user3783952 - 6 months ago 16
jQuery Question

Stop division from losing focus

I have an autocomplete feature attached to an input tag with id keyword. The results of the autocomplete are visible in the division with id results and each result item inside a division with class item.
Here is the HTML markup:

<input name='institute' type="text" placeholder="Start typing.."id="keyword">
<div id="results">
<div class="item"><p>Item 1</p></div>
<div class="item"><p>Item 2</p></div>
<div class="item"><p>Item 3</p></div>
</div>


The division results has a fixed height. Here is the CSS:

width:80%;
height: 200px;
overflow-y: auto;


Here is my the part of the jquery relevant to my question

$("#keyword").blur(function() {
$("#results").fadeOut(500);
})
.focus(function() {
$("#results").show();
});


Now the problem occurs whenever the height of the results exceeds from 200px. I get a scroll but whenever i click of the scroll, the input tag keyword looses its focus and the division results fades away. I want to keep the division results when I use the scroll and fade it only after an item is selected. How do I fix it?

Answer

Interesting question, and a real challenge to get to work in both Chrome and IE:

var canBlur= true;

$('#results')
  .mousedown(function(event) {
    canBlur= event.target.id !== 'results';
  })

$(document)
  .mousemove(function() {
    if(!canBlur) {
      $('#keyword').focus();
    }
    canBlur= true;
  });

$('#keyword')
  .blur(function(event) {
    if(canBlur) {
      $('#results').fadeOut(500);
    }
  })
  .focus(function() {
    $('#results').fadeIn(0);
  })

Fiddle