3

I have a piece of JavaScript which I use to search my site. When you type into the search it pulls up the products matching you query. This works fine, 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 will 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");
}
yuvi
  • 18,155
  • 8
  • 56
  • 93
  • possible duplicate of [How to detect a click outside an element?](http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element) – John Sterling Aug 02 '14 at 11:33

2 Answers2

1

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();
});
Engin Üstün
  • 1,118
  • 11
  • 18
AmanVirdi
  • 1,667
  • 2
  • 22
  • 32
0

Use this:

$("#smartSearchDiv").click(function(e){
    e.stopPropagation();
});    

$(body).click(function(){
     if($("#smartSearchDiv").is(":visible")){
         hideSmartSearch();
     }
});

This way, if you click on your search div, event will stop propagation to its parents, and nothing will happen. Otherwise, it will go upto your body and fire a close function.

Eternal1
  • 5,447
  • 3
  • 30
  • 45