From 011b8329a9e9643509dae452c15fe57ccbebb476 Mon Sep 17 00:00:00 2001 From: Jen Gorfine Date: Wed, 9 Feb 2022 11:48:33 -0500 Subject: [PATCH] feat: added escape key responses to search input and clear button --- script.js | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/script.js b/script.js index e9ba8b81d..f786d01f8 100644 --- a/script.js +++ b/script.js @@ -21,6 +21,15 @@ function clearSearchInput() { searchInput.focus(); } +// Have the search input and clear button respond +// when someone presses the escape key, per: +// https://twitter.com/adambsilver/status/1152452833234554880 +function clearSearchInputOnEscape(event) { + if (event.key === "Esc") { + clearSearchInput(); + } +} + // Create an HTML button that all users -- especially keyboard users -- // can interact with, to clear the search input. // To learn more about this, see: @@ -33,10 +42,11 @@ function buildClearSearchButton() { const icon = ``; button.innerHTML = icon; button.addEventListener("click", clearSearchInput); + button.addEventListener("keyup", clearSearchInputOnEscape); return button; } -// Append the clear button to the search field +// Append the clear button to the search form function appendClearSearchButton() { searchClearButton = buildClearSearchButton(); searchForm.append(searchClearButton); @@ -45,6 +55,19 @@ function appendClearSearchButton() { } } +// Add a class to the search form when the input has a value; +// Remove that class from the search form when the input doesn't have a value. +// Do this on a delay, rather than on every keystroke. +const toggleClearSearchButtonAvailability = debounce(function() { + searchForm.classList.toggle(searchFormFilledClassName, searchInput.value.length > 0); +}, 200) + +// Ensure the search field responds appropriately to typing + keyboard interactions +function handleSearchInputKeyup(event) { + clearSearchInputOnEscape(event); + toggleClearSearchButtonAvailability(); +} + document.addEventListener('DOMContentLoaded', function() { // Key map var ENTER = 13; @@ -71,11 +94,8 @@ document.addEventListener('DOMContentLoaded', function() { // Set up clear functionality for the search field searchForm = document.querySelector("form[role='search']"); - const toggleClearSearchButtonVisibility = debounce(function(event) { - searchForm.classList.toggle(searchFormFilledClassName, event.target.value.length > 0); - }, 200) searchInput = searchForm.querySelector("input[type='search']"); - searchInput.addEventListener("keyup", toggleClearSearchButtonVisibility); + searchInput.addEventListener("keyup", handleSearchInputKeyup); appendClearSearchButton(); // social share popups