Search code examples
javascriptjquerysearch-engine

Press Esc button to close suggestion list


When user presses Esc button, I hope that the suggestion list will be closed.

How can I do this?

This are my codes:

  1. script_suggestion.php:

    <script type="text/javascript">
    
        //document.getElementById("suggestion")
    
        function getSuggestion(q) {
            var ajax;
            if(window.XMLHttpRequest)//for ie7+, FF, Chrome
                ajax = new XMLHttpRequest();//ajax object
            else
                ajax = new ActiveXObject("Microsoft.XMLHTTP");//for ie6 and previous
            ajax.onreadystatechange = function() {
                if(ajax.status === 200 && ajax.readyState === 4) {
                    //if result are not there then don't display them
                    if(ajax.responseText === "")
                        document.getElementById("suggestion").style.visibility = "hidden";
                    else {
                        document.getElementById("suggestion").style.visibility = "visible";
                        document.getElementById("suggestion").innerHTML = ajax.responseText;
                    }
                }
            };
            ajax.open("GET", "suggestion.php?q=" + q, false);
            ajax.send();
        }
    </script>
    

  2. PHP Code:

    <?php include 'script_suggestion.php'; include 'script_close_suggestion_box.php'; ?>

Thanks in advance.


Solution

  • Use this :

    var forceClose = false;
    
    function getSuggestion(q) {
    
        if (!forceClose) {
    
            var ajax;
            if (window.XMLHttpRequest)//for ie7+, FF, Chrome
                ajax = new XMLHttpRequest();//ajax object
            else
                ajax = new ActiveXObject("Microsoft.XMLHTTP");//for ie6 and previous
            ajax.onreadystatechange = function () {
                if (ajax.status === 200 && ajax.readyState === 4) {
                    //if result are not there then don't display them
                    if (ajax.responseText === "")
                        document.getElementById("suggestion").style.visibility = "hidden";
                    else {
                        document.getElementById("suggestion").style.visibility = "visible";
                        document.getElementById("suggestion").innerHTML = ajax.responseText;
                    }
                }
            };
            ajax.open("GET", "suggestion.php?q=" + q, false);
            ajax.send();
    
        }
    }
    
    window.document.onkeydown = function (e) {
        if (!e) e = event;
        if (e.keyCode == 27) {
            document.getElementById("suggestion").style.visibility = "hidden";
            forceClose = true;
        }
    };