Hide search input field and search results when user clicks on them

How to hide both the input field and the search results window when the user clicks on them?

Currently, if you hover over , both and #search-btnwill appear . If you click anywhere except both disappear.#search-container#search-results#search-container

I want so that I can click #search-resultsso that both of them do not disappear.

Fiddle: https://jsfiddle.net/emils/d2sn7q6L/

HTML:

<div id="search-container">
  <form id="search-form">
    <input id="search" type="search">
  </form>
</div> <!-- End search-box -->

<a id="search-btn" class="search-icon" href="#">search</a>

<div id="search-results"></div> <!-- End search-results -->

JS:

var searchInput = $("#search-container");
var searchResults = $("#search-results");

var showSearchInput = function() {
  searchInput.show();
  searchResults.show();
  if(searchInput.is(":visible")) {
    $("#search").focus();
  }
};
$("#search-btn").hover(showSearchInput);

searchInput.focusout(function(e) {
  searchInput.hide();
  searchResults.hide();
});
+4
source share
4 answers

$(document) .is( "hover" ) , - , , , , , :

$(document).click(function(){ //if the document has been clicked
if( !($("#search-container").is(":hover"))&&
    !($("#search-results").is(":hover"))&&
    !($("#search-btn").is(":hover"))
   )//if any of these elements have the mouse then me know the user didn't click on them
{searchInput.hide();searchResults.hide();}}//hide the boxes

, ,

+1

, , .

$(document).click(function(evt) {
  if ($(evt.target).closest('#search-container, #search-results').length == 0) {
    searchInput.hide();
    searchResults.hide();
  }
});

. : https://jsfiddle.net/L4ne5r2w/

+1

searchInput.focusout :

$(document).on('click', function (e) {
    if($(e.target).attr('id') != "search-results") {
        searchInput.hide();
        searchResults.hide();
    }
});

, , searchResults.

+1

Although I do not like the idea of ​​hiding the search field;) this may be necessary for your project, but in the example above, it .on("focusout", function ...does the job. As an optimization, I would suggest wrapping them in a container so as not to call show () and hide () twice to iterate at least ...

0
source

Source: https://habr.com/ru/post/1664445/


All Articles