Ruby on Rails keyboard shortcuts

前端 未结 3 1941
盖世英雄少女心
盖世英雄少女心 2020-12-30 15:10

does anyone know how to set-up keyboard shortcuts using Ruby on Rails on my website? For example if a user want to interact with the site using keyboard shortcuts instead of

相关标签:
3条回答
  • 2020-12-30 15:36

    Look on this page about keyboard shortcuts to a web application. This site supplies a .js that performs this functionality.

    0 讨论(0)
  • 2020-12-30 15:40

    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.

    0 讨论(0)
  • 2020-12-30 15:58

    You can use any JavaScript library to provide keyboard shortcuts. Since Rails uses Prototype by default (for the JavaScript helper methods), you might want to check out prototype-hotkeys.

    There are some usage examples in that website.

    0 讨论(0)
提交回复
热议问题