Search code examples
javascriptjqueryjquery-pluginsjquery-click-event

Jquery click outside the element to hide other element


Haai. I have a problem. How to I hide this button when I click outside of <input type="search">. The button show when I click <input type="search">but I don't know how to hide the button when we click outside the <input type="search">. Any idea?

HTML

<input type="search">
<button type="submit" class="search_btn" name="button">Search</button>

Jquery

 $("input[type='search']").click(function() {
   $(".search_btn").addClass("search_on");
 });
 $("*:not('input[type='search']')").click(function() {
   $(".search_btn").removeClass("search_on");
 });

Solution

  • UseremoveClass

    $(document).on('click', function(event) {
      if (event.target.id !== 'submitButton' && event.target.id !== "search") {
        $(".search_btn").removeClass("search_on");
      }
    
    })
    $("input[type='search']").on({
      click: function() {
        $(".search_btn").addClass("search_on");
      }
    });
    $("#submitButton").click(function() {
      console.log($("#search").val())
    })
    .search_btn {
      display: none
    }
    
    .search_on {
      display: inline-block;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="search" id="search">
    <button type="submit" id="submitButton" class="search_btn" name="button">Search</button>