Skip to content

Instantly share code, notes, and snippets.

@alystair
Created March 12, 2020 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alystair/9e637d9328eca12e980073c511ece85d to your computer and use it in GitHub Desktop.
Save alystair/9e637d9328eca12e980073c511ece85d to your computer and use it in GitHub Desktop.
Override enter key on longer forms and move to next input (not quite finished)
document.addEventListener('keydown', function () {
// Prevent enter key from submitting form if they are large
if (event.keyCode === 13 && event.target.nodeName !== 'TEXTAREA') {
let form = event.target.closest('form');
if (form && form.children.length > 10) { // Only large forms
event.preventDefault();
// If only one could just send a simulated tab key event to shift to next active field...
let startingNode = event.target.nextElementSibling || event.target.parentElement.nextElementSibling; // will break if final?
let foundStart = false;
function onlyInputs(node) {
if (!foundStart && node !== startingNode) return NodeFilter.FILTER_REJECT;
else foundStart = true;
if (node.offsetHeight === 0 && node.offsetWidth === 0) return NodeFilter.FILTER_REJECT;
// node.querySelector('input, textarea, select');
let found = ['INPUT', 'TEXTAREA', 'SELECT'].includes(node.nodeName) && node.type !== 'hidden';
return found ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}
let nodeIterator = document.createNodeIterator(form, 1, onlyInputs);
nodeIterator.nextNode().focus();
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment