0

I have some code that opens and closes a window. This window has a search bar (input) that gets focus when the window is opened. Closing by pressing Esc only works when the focus is on the input. When there is no focus, Esc does not work. Why?

   const btn = document.querySelector('.header-left__search-btn'),
        body = document.body,
        search = document.querySelector('.search'),
        searchInput = document.querySelector('#search__input'),
        btnClose = document.querySelector('.search__closed-icon');

    function searchOpen() {
        btn.addEventListener('click', () => {
            body.classList.add('is-search-open');
            setTimeout(() => {
                searchInput.focus(); 
            }, 300);
            if (body.classList.contains('is-head-open')) {
                body.classList.remove('is-head-open');
            }  
        });

        search.addEventListener('keydown', (e)  => {          
            if(e.code === "Escape" && body.classList.contains('is-search-open')) {
                body.classList.remove('is-search-open');

            }
        });

        btnClose.addEventListener('click', function ()  {
            body.classList.remove('is-search-open');
        });
    }
    searchOpen();
  • 2
    you're adding **eventListener** on `search`, which I am assuming is the input field. eventListener will only trigger on input focus. Add the escape eventListener outside `search` – ahsan Sep 15 '21 at 07:11
  • Add the key listener to the document instead, and handle the situation appropriately. i.e. in the escape listener, if the popup is visible, close it. To answer your question: only focused elements react to keypress events. –  Sep 15 '21 at 07:13
  • Add the listener to `document` or `window`, only form control elements trigger `keydown` by default. – Teemu Sep 15 '21 at 07:14
  • `search` is window, my input is variable `searchInput ` – Леонид Колтан Sep 15 '21 at 07:15
  • You need to add the listener to `document` or `window`. It won't work on arbitrary divs. –  Sep 15 '21 at 07:16

1 Answers1

0

This is because you bound your event to the html element with the class .search (Which I guess is your input field).

If you want to intercept the ESC button no matter what is focused, add your keydown event listener to document.

rémy
  • 1,026
  • 13
  • 18