The simplest way is to set a value for the accesskey
attribute for your elements. If you wanted to do this through Rails, you could do this by passing an extra option to the submit_tag
helper method, like so:
<%=submit_tag("Save and Refresh", :accesskey => "R") %>
// Equivalent to <input type="submit" value="Save and Refresh" accesskey="R" />
Which will cause that button to be "clicked" when Alt+R (or Alt+Shift+R, depending on your browser) is pressed. The accesskey
attribute is available for <input>
, <button>
and <a>
HTML elements.
If you are looking to do something more complex (like GMail's keyboard shortcuts, for example), you will have to write some javascript. The core of it would be an event handler that watches for keypresses on the document, and then calls other javascript functions to run the code that you want when a certain key is pressed. Here's a very simplistic way of setting up shortcuts based on a key press (this uses Prototype, which is the Javascript library that Rails uses by default, and is untested):
$(document.body).observe("keypress", function(event)
{
var keyCode = event.which || event.keyCode; // W3C and Microsoft's event models
// have differing ways of
// determining which key was pressed
var keyChar = String.fromCharCode(keyCode); // turn a code into an actual character
switch (keyChar)
{
case 'a':
// Run code if the user presses 'a'
break;
// ...
}
});
Here is another SO question that deals with keyboard shortcuts in Javascript.
Note that neither of these solutions really rely on Rails at all.