Friday, October 21, 2022

Key event to focus box with keyboard

Focus search-box with keyboard key:

(function focusSearch() {
document.addEventListener(
'keypress',
(e) => {
const name = e.key;
const code = e.code;
console.log(`Key pressed ${name} \r\n Key code value: ${code}`);
console.log(e);
if (e.code === 'Enter') {
window.scrollTo(0, 0, { behavior: 'smooth' }); // scroll to top
document.querySelector('.search').focus();
}
},
false
);
})();

//

No comments:

Post a Comment