I can’t figure out what’s going on. Below is the JS code that is responsible for closing and opening the search box running in the JS application. Closing occurs by pressing a button with a cross, Esc keyboard and anywhere in this window
const btn = document.querySelector('.head__search-icon'),
body = document.body,
search = document.querySelector('.search'),
searchInner = document.querySelector('.search__inner'),
searchOverlay = document.querySelector('.search__overlay'),
searchInput = document.querySelector('#search__input'),
btnClose = document.querySelector('.search__closed-button');
body.classList.add('no-search'),
search.style.display = 'none';
function searchOpen() {
btn.addEventListener('click', () => {
body.classList.remove('no-search');
body.classList.add('is-search');
search.style.display = 'block';
setTimeout(() => searchInput.focus(), 100);
if (body.classList.contains('is-head-open')) {
body.classList.remove('is-head-open');
}
});
}
searchOpen();
function searchClose() {
body.classList.add('no-search');
body.classList.remove('is-search');
searchInput.value = '';
searchInput.blur();
}
function searchRemove(e) {
if(e.code === "Escape" && body.classList.contains('is-search') || e.target === searchOverlay || e.target === searchInner) {
searchClose();
}
}
document.addEventListener('keydown', searchRemove);
search.addEventListener('click', searchRemove);
btnClose.addEventListener('click', searchClose);
The fact is that if there is a search result, and press Esc, then everything works, the focus from the input disappears, and the input itself is cleared. But if you click anywhere in the window ( e.target === searchOverlay || e.target === searchInner ), then the window itself closes, the input is cleared, as I need, except that with a visually clean input, the search results remain. That is, you open the window again and see the same search results, although the input is empty. When working with Esc, the input is actually cleared. Where is the jamb in the script?