Javascript doesn't close the menu
I have a piece of JavaScript that I am using to search my site. When you enter a search, it pulls up products that match your query. This works great, but I want the dropdown to close when the user clicks on the page. I know very little about JavaScript, so any advice or even a point in the right direction would be appreciated.
function showSmartSearch() {
$.ajax({
url: "index.php?route=product/ajaxsearch&search=" + $("input[name='search']").val(),
type: "GET",
success: function(e) {
$("#smartsearchdiv").css("display", "block");
var t = "";
$("#smartsearchdiv").html(e)
}
})
}
function hideSmartSearch() {
$("#smartsearchdiv").css("display", "none")
}
var wait;
$(document).ready(function() {
$("input[name='search']").after('<div id="smartsearchdiv" style="margin-top:30px;background:white;width:230px;position:absolute;z-index:999;"></div>').blur(function() {}).keydown(function(e) {
if ($("input[name='search']").length && e.which == 38) {
e.preventDefault();
return false
}
}).keyup(function(e) {
if (!$("input[name='search']").val()) {
$("#smartsearchdiv").css("display", "none")
}
var t = $("input[name='search']").val();
var n = t.length;
if (t.replace(/^\s+|\s+$/g, "") && (e.which == 8 || 47 < e.which && e.which < 112 || e.which > 185)) {
if (n > 0) {
showSmartSearch()
} else {
hideSmartSearch()
}
}
if ($("#smartsearchdiv li").length && (e.which == 38 || e.which == 40)) {}
}).blur(function() {})
});
function hideSmartSearch() {
$("#smartsearchdiv").css("display", "none");
}
+3
source to share
2 answers
You can try this:
$(document).click(function(e){ // hide list if clicked outside
if($(e.target).is('#smartSearchDiv, #smartSearchDiv *'))return;
hideSmartSearch();
});
Also this:
$(document).click(function(e){ // hide list if clicked outside
if(!$(e.target).is('#smartSearchDiv'))
hideSmartSearch();
});
+1
source to share
Use this:
$("#smartSearchDiv").click(function(e){
e.stopPropagation();
});
$(body).click(function(){
if($("#smartSearchDiv").is(":visible")){
hideSmartSearch();
}
});
This way, if you click on your search, the event will stop propagating to the parents and nothing will happen. Otherwise it will go to yours body
and run the close function.
0
source to share