Last active
December 22, 2015 09:28
-
-
Save XORwell/6451826 to your computer and use it in GitHub Desktop.
mousetrap jquery data-keybinding example
This file contains hidden or 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
| /** | |
| * Mousetrap example | |
| * provides data-keybinding property | |
| * | |
| * requirements: jQuery, Mousetrap (https://github.com/ccampbell/mousetrap) | |
| * | |
| * examples: | |
| * 1: <input type='text' data-keybinding='ctrl+shift+f'> <!-- ctrl+shift+f will focus this input element --> | |
| * 2: <button type='button' data-keybinding='ctrl+shift+b'>save</button> <!-- ctrl+shift+b will click this button --> | |
| * 3: <input type='submit' data-keybinding='ctrl+shift+s'> <!-- ctrl+shift+s will click this input element --> | |
| */ | |
| $(function(){ | |
| //////////////////////////////////////////////////////////////////// | |
| // Hotkey binding to elements with 'data-keybinding' attribute: trigger click-event when hotkey pressed | |
| clickable_selectors = [ | |
| 'a[data-keybinding]', | |
| 'input[data-keybinding][type="submit"]', | |
| 'input[data-keybinding][type="button"]', | |
| 'button[data-keybinding][type="button"]' | |
| ] | |
| $(clickable_selectors).each(function(i, selector){ | |
| $(selector).each(function(i, el){ | |
| Mousetrap.bind($(el).data('keybinding'), function(e){ | |
| el.click(); | |
| }); | |
| }) | |
| }) | |
| ////////////////////////////////////// | |
| // Hotkey binding to elements with 'data-keybinding' attribute: trigger focus on these elements | |
| focusable_selectors = [ | |
| 'input[data-keybinding][type="text"]', | |
| 'textarea[data-keybinding]', | |
| ] | |
| $(focusable_selectors).each(function(i, selector){ | |
| $(selector).each(function(i, el){ | |
| Mousetrap.bind($(el).data('keybinding'), function(e){ | |
| el.focus(); | |
| }); | |
| }) | |
| }) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment