Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

Javascript: handling keyboard shortcuts with jQuery

Last few years the JavaScript frameworks are big part of our web sites. I strongly recommend the usage of tools like jQuery or MooTools, because they will save you a lot of time and problems. These days I needed to create a keyboard shortcut for one of the projects that I'm working on. I wanted to catch the Ctrl+Shift+F9 combination. It was just a few lines of code and I decided to share it with you.

// defining flags
  var isCtrl = false;
  var isShift = false;
  // helpful function that outputs to the container
  function log(str) {
    $("#container").html($("#container").html() + str + "");
  };
  // the magic :)
  $(document).ready(function () {
    log("Ready. Press Ctrl+Shift+F9!");
    // action on key up	
    $(document).keyup(function (e) {
      if (e.which == 17) {
        isCtrl = false;
      }
      if (e.which == 16) {
        isShift = false;
      }
    });
    // action on key down	
    $(document).keydown(function (e) {
      if (e.which == 17) {
        isCtrl = true;
      }
      if (e.which == 16) {
        isShift = true;
      }
      if (e.which == 120 && isCtrl && isShift) {
        log("------- catching Ctrl+Shift+F9");
      }
    });
  });
If you enjoy this post, share it on Twitter, Facebook or LinkedIn.