Last active
May 10, 2024 15:02
-
-
Save stevelacey/3fd901b7bde31538cd15 to your computer and use it in GitHub Desktop.
KeyHook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
var KeyHook = { | |
init: function(e) { | |
if (e.keyCode == 13) { | |
if (!e.target || !e.target.form) return; | |
var button; | |
if (this.isSubmitButton(e.target)) { | |
button = e.target; | |
} else { | |
button = this.getSubmitButton(e.target.form); | |
} | |
if (button) { | |
var e = document.createEvent('HTMLEvents'); | |
e.initEvent('click', true, true); | |
button.dispatchEvent(e); | |
} | |
} | |
}, | |
getSubmitButton: function(form) { | |
var els = form.querySelectorAll('button, input'); | |
for (var i = 0; i < els.length; i++) { | |
if (this.isSubmitButton(els[i])) return els[i]; | |
} | |
return null; | |
}, | |
isSubmitButton: function(el) { | |
var tag = el.tagName.toLowerCase(); | |
var type = el.getAttribute('type') ? el.getAttribute('type').toLowerCase() : undefined; | |
return tag == 'button' && type == 'submit' || tag == 'input' && (type == 'image' || type == 'submit'); | |
}, | |
bind: function() { | |
var els = document.querySelectorAll('input, button, select'); | |
for (var x = 0; x < els.length; x++) { | |
els[x].addEventListener('keydown', listener, false); | |
} | |
}, | |
unbind: function() { | |
var els = document.querySelectorAll('input, button, select'); | |
for (var x = 0; x < els.length; x++) { | |
els[x].removeEventListener('keydown', listener, false); | |
} | |
} | |
}; | |
function listener(e){ | |
KeyHook.init(e); | |
} | |
KeyHook.bind(); | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment