Edit and save shortcuts with jQuery for Drupal 7 [update]

Estimated reading time of this article: 1 minute 56 seconds

How to add an edit key shortcut for Drupal 7?

I'm used to work with keyboard shurtcuts for common tasks. Drupal 7 does not support shortcuts out-of-the-box.

I've written a small jQuery script which maps the key e to the edit node action and Ctrl s to save on the node form.

Edit shortcut e

  /**
   * Map key 'e' to edit node.
   * Pressing the key 'e' on a node will load the node edit form.
   */
  Drupal.behaviors.shortcuts = {
    attach: function (context, settings) {
      $('body', context).keypress(function(event) {
         var url;
        if (event.charCode == 101 && (url = $('link[rel=shortlink]').attr("href")) != undefined) {
          window.location.href = url + '/edit';
         } else if (event.charCode == 101 && (url = $('some selector…').first().attr("href")) != undefined) {
          window.location.href = url;
        }
     });
    }
  };

101 is the charCode of e.

This little script must be loaded on the Drupal page. It can automatically be added by the following line in your .info file of your theme:

  scripts[]   = js/shortcuts.js

Save shortcut Ctrl s

I've written a little Javascript which simulates the clicking of the save button (the first one) on the Ctrl-S key event.

(function ($) {

  /**
   * In node forms on Ctrl-S click the first action button.
   */
  Drupal.behaviors.shortcuts = {
    attach: function (context, settings) {
      // Key codes: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
      //alert("Drupal Ctrl-S activated");
      $(window, context).keypress(function(event) {
        //console.log( event );
        if ((event.ctrlKey && event.which == 115) || (event.which == 19)) {
          event.preventDefault();
          //alert("Save");
          // Save is with Save as Draft module always at first position
          $('.node-form #edit-actions input').first().click();
          // Do not trigger default behaviour of Firefox
          // Ref: http://stackoverflow.com/questions/93695/best-cross-browser-method-to-capture-ctrls-with-jquery
          return false;
        }
      });
    }
  };

})(jQuery);

Save the script as js/shortcut.js.

Load the script via a node form alter hook in your module.

<?php
/**
 * Implements hook_form_FORM_ID_alter().
 * Adapted from save_draft.module
 */
function YOUR_MODULE_form_node_form_alter(&$form, &$form_state) {
 
// Add js on node form
 
$form['actions']['submit']['#attached']['js'] = array(
   
drupal_get_path('module', 'YOUR_MODULE') . '/js/shortcut.js',
  );
}
?>

Do not forget to run update.php in order to register the new hook.

This solution is compatible with the Save as Draft module.

The module Form Save allows saving of forms with Ctrl s. The module Keyboard shortcuts allows the setting of shortcuts. I haven't used either of them.