javascriptjqueryfocusout

Blur exception based on clicked element


enter image description here

How it works

I am building a demo search box where the search results show up when the input field is not empty while focusing in. When you blur the search results container hides.

Problem

The problem appears when I click the search results container. The input field blurs with the result that the search results container hides.

How to make it work so that the search results container does not hide when clicking it (or an element inside it).

HTML

<div class="searchbox">
   <input class="input">
   <div class="search-results">
      // Results
   </div>
</div><!--End .searchbox-->

jQuery

$('.searchfield .input').focusin(function() {

   // When value is not empty show search results
   if ($(this).val() !== '') {
      $('.searchbox .search-results').fadeIn(10);
   }

   // Other code

}).focusout(function() {

   // Hide search results
   $('.searchbox .search-results').fadeOut(10);

   // Other code

});

Solution

  • I fixed my problem by adding a delay on the fadeout during the blur. This way I was able to click the button inside the container.

    $('.searchfield .input').focusin(function() {
    
       // When value is not empty show search results
       if ($(this).val() !== '') {
          $('.searchbox .search-results').fadeIn(10);
       }
    
       // Other code
    
    }).focusout(function() {
    
       // Hide search results
       $('.searchbox .search-results').delay(300).fadeOut(10);
    
       // Other code
    
    });