简体   繁体   中英

let dropdown menu disappear if I click outside

I have this search box search box

And I've written a function to let the search box disappear when the user clicks outside or presses the Esc button.

The problem is, that when the user clicks on the search field, then search button "Suchen" in the menu does not disappear.

after search

My code:

//Outside click
$("body").click(function(){
    jQuery('.searchfieldbox').fadeOut(500);
});
$("body").keydown(function(e){
    if(e.keyCode === 27 || e.which === 27 ){
        jQuery('.searchfieldbox').fadeOut(500);
    }
});
$(".pg-suche-lupe-button").click(function(e){
    e.stopPropagation();
});

How can solve this problem ???

Try to make use of $(e.target).hasClass on the body click.

Stack Snippet

 $("body").click(function(e) { if (!$(e.target).hasClass("searchfieldbox")) { jQuery('.searchfieldbox').fadeOut(500); } }); $("#input").click(function(e) { e.stopPropagation(); jQuery('.searchfieldbox').fadeIn(500); }); $("body").keydown(function(e) { if (e.keyCode === 27 || e.which === 27) { jQuery('.searchfieldbox').fadeOut(500); } }); 
 .searchfieldbox { height: 100px; background: #ccc; width: 100px; display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="input"> <div class="searchfieldbox"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM