jQuery function that closes the search field by clicking Esc

1

On the site I'm developing, there's a search field that only shows input when you click on the button.

Now I want to close the input when I click the Esc key (when the focus is in the field). I have done a function in jQuery, but it is not working:

FUNCTION:

$('#campo-pesquisa').keypress(function(e) {
    if(e.keyCode === 27) $('#fechar-campo').click();
});

HTML CODE

<div class="form-pesquisa">
                    <form class="input-group" id="campo-pesquisa" action="{{ url }}busca">
                        <input type="text" class="form-control border-right-0" id="input-pesquisa" name="q"
                               aria-label="Campo de busca" placeholder="O que deseja procurar?">
                        <div class="input-group-append">
                            <span class="input-group-text" id="search">
                                <button type="submit">
                                    <span class="ocultaVisualmente">Buscar</span>
                                    <i class="fas fa-search"></i>
                                </button>
                            </span>
                            <span class="input-group-text" id="close-pesquisa">
                                <button type="reset" id="fechar-campo">
                                    <span class="ocultaVisualmente">Fechar Campo de Pesquisa</span>
                                    <i class="fas fa-times"></i>
                                </button>
                            </span>
                        </div>
                    </form>
                </div>
    
asked by anonymous 11.06.2018 / 22:48

1 answer

1

The keypress only detects keys with printable characters (letters, numbers, space, etc.).

MDN Documentation:

Use% of% to detect all keys, then the ESC key will be detected:

$('#campo-pesquisa').keydown(function(e) {
    if(e.keyCode === 27) $('#fechar-campo').click();
});
    
11.06.2018 / 22:59