Home > OS >  Make Search Box closes if user clicks anywhere?
Make Search Box closes if user clicks anywhere?

Time:07-30

Currently, the search box opens and closes on clicking the font awesome search icon. But I want the search box closed when the user clicks anywhere inside the body...

My Code:

button.search-open {
    position: absolute;
    z-index: 999;
    background-color: transparent;
    border: none;
    padding: 8px 20px;
    font-size: 20px;
    color: #fff;
    top: 10px;
    margin-left: 1225px;
    border-radius: 4px;
    cursor: pointer;
}

     <button >
       <i  aria-hidden="true"></i>
       <i  aria-hidden="true"></i>
     </button>
    <div >
       <form action="<?php echo home_url( '/' ); ?>">
         <h3>Type Here To Search</h3>
           <label>
            <input type="text" name="s" placeholder="Search...">
            <button type="submit" ><i  aria-hidden="true"></i></button>
             </label>
          </form>
         </div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
        $(".search-open").click(function() {
            $('.search-box').toggle();
            $('.search-open .fa-search, .search-open .fa-times').toggle();
        });
  });
</script>

Thanks in advance :)

CodePudding user response:

Maybe you can try something like this. Let me know

$(document).ready(function() {
 $('.search-open').click(function(){
    $('.search-box').toggle();
     $('.search-open .fa-search, .fa-times').toggle();
    
});
});
$(document).click(function(e) {   
    if(e.target.id != 'search') {
        $(".search-box").hide();   
          
    } 

});
.search-box {display:none}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="search" >
       <i  aria-hidden="true"></i>
       <i  aria-hidden="true"></i>
     </button>
    <div  >
       <form action="<?php echo home_url( '/' ); ?>">
         <h3>Type Here To Search</h3>
           <label>
            <input type="text" name="s" placeholder="Search...">
            <button type="submit" ><i  aria-hidden="true"></i></button>
             </label>
          </form>
         </div>

  • Related