Skip to content

Instantly share code, notes, and snippets.

@XORwell
Last active December 22, 2015 09:28
Show Gist options
  • Save XORwell/6451826 to your computer and use it in GitHub Desktop.
Save XORwell/6451826 to your computer and use it in GitHub Desktop.
mousetrap jquery data-keybinding example
/**
* 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