The recipe box has a labeled search field and a normal Search button. Add a keyboard shortcut for Enter in the field; keep ordinary keys and Tab available.
The separate museum-search example only cancels Enter on the field and cancels the form’s submit event for button activation. The early return matters: if you call preventDefault for every key, you block normal typing and can interfere with navigation. The form listener also prevents an actual page navigation when someone uses its submit button. Keep the provided role="status" element for the result.
// Different example: a museum catalogue, not your recipe box.
function showArtwork() { output.textContent = "Find: " + query.value.trim(); }
query.addEventListener("keydown", function (event) {
if (event.key !== "Enter") return;
event.preventDefault();
showArtwork();
});
museumForm.addEventListener("submit", function (event) {
event.preventDefault();
showArtwork();
});
Type Bread and press Enter: the result should read Finding: Bread, without navigation. Press Tab afterward; focus should still move away from the field. Activating Search with mouse or keyboard should produce the same result.
The earlier click and delegation lessons relied on native buttons. This shortcut adds behavior to a text field while preserving the browser’s other keyboard behaviors.
#recipe receives Enter on keydown, prevent only that default, leave Tab and ordinary keys uncanceled, and set #recipe-result to Finding: followed by the trimmed field value.#recipe-form submit by preventing page navigation and showing the same trimmed result for button activation.Return for non-Enter keys before calling preventDefault.