1

I used toggle to make a search form from a button. But I want click outside any position to close search form, not only using button.

HTML

<a href="#" data-mini="false" data-theme="e" data-role="button" class="opensearch" data-icon="search" data-iconpos="right">Search</a>
<div class="search_field" style="display:none;">
    <form>
        <input name="search" class="search" value="" placeholder="Search Item...." type="text" data-theme="e" />
        <input type="submit" value="Search" data-mini="false" data-icon="search" data-iconpos="notext" data-theme="c" />
    </form>
</div>

Jquery :

 $(function() {
     $(".opensearch").on('click', tapHandler);
     function tapHandler(event) {
         $('.search_field').toggle();
         $('.search').focus();
     }
 });

Demo of JsFiddle

Many thanks for your help.

Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63
Hai Tien
  • 2,929
  • 7
  • 36
  • 55

2 Answers2

4

Use the blur event:

$(".search").on("blur",function(){
    $('.search_field').toggle();
});

Updated fiddle: JsFiddle demo


[Edit] You might want to check if the new focus is not on the search icon before hiding the field:

$(".search").on("blur",function(){
  setTimeout(function(){
    var target = document.activeElement;
    target = target ? target.id||target.tagName||target : '';

    if(target!="INPUT"){
        $('.search_field').toggle();
    }

  }, 1);        
});

Better with the id of the button though....

Example: JsFiddle demo

urbz
  • 2,663
  • 1
  • 19
  • 29
Mr.Manhattan
  • 5,315
  • 3
  • 22
  • 34
1

You can do something like

 $(function() {

   $(".opensearch").on('click', tapHandler);
   //add a click handler to the document object
   $(document).on('click', function(e) {
     //if the click is happening inside the search_field or opensearch elements then don't do anything
     if ($(e.target).closest('.search_field, .opensearch').length == 0) {
       $('.search_field').hide();
     }
   });

   function tapHandler(event) {
     $('.search_field').toggle();
     $('.search').focus();
   }

 });
.search_field {
  padding: 10px 10px 0;
  position: relative;
}
.search_field .ui-submit {
  bottom: -2px;
  position: absolute;
  right: 18px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" data-mini="false" data-theme="e" data-role="button" class="opensearch" data-icon="search" data-iconpos="right">Search</a>

<div class="search_field" style="display:none;">
  <form>
    <input name="search" class="search" value="" placeholder="Search Item...." type="text" data-theme="e" />
    <input type="submit" value="Search" data-mini="false" data-icon="search" data-iconpos="notext" data-theme="c" />
  </form>
</div>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531