0

I've tried all the ways from the answers here, but have not worked. So far I have done:

jQuery(function($) {
  $(document).ready(function(){
      $("#sb-search").click(function(){
          $(".sb-search").addClass("sb-search-open");
          $("body").click(function(){
              $(".sb-search").hasClass("sb-search-open");
              $(this).removeClass("sb-search-open");
          });
      });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="sb-search" class="sb-search">
    <form autocomplete="off" action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
        <input class="sb-search-input" type="search" value="" name="s" id="s">
        <input class="sb-search-submit" type="submit" value="">
        <span class="sb-icon-search"></span>
    </form>
</div>
</body>

I want to remove the .sb-search-open class after clicked outside the div

Maistrenko Vitalii
  • 994
  • 1
  • 8
  • 16
Samber Pelix
  • 13
  • 2
  • 10

1 Answers1

1

jQuery(function($) {
  $(document).ready(function(){
      $("#sb-search").click(function(e){
           e.stopPropagation();
          $(".sb-search").addClass("sb-search-open");

      });
      $("body").click(function(){
              $(".sb-search").removeClass("sb-search-open");
              console.log('body')
       });
  });
});
html,body{
  height:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="sb-search" class="sb-search">
    <form autocomplete="off" action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
        <input class="sb-search-input" type="search" value="" name="s" id="s">
        <input class="sb-search-submit" type="submit" value="">
        <span class="sb-icon-search"></span>
    </form>
</div>
</body>

First remove click listener on body out side the input click listener. in input click listener add e.stopPropagation() to stop bubbling of event

jQuery(function($) {
  $(document).ready(function(){
      $("#sb-search").click(function(e){
           e.preventDefault();
           e.stopPropagation();
          $(".sb-search").addClass("sb-search-open");

      });
      $("body").click(function(){
              $(".sb-search").removeClass("sb-search-open");
       });
  });
});
Punith Jain
  • 1,647
  • 1
  • 15
  • 21