3

I have been writing a sort of online spreadsheet application for a specific purpose and along with it I have written my own undo and redo functions. When the user presses ctr-z or ctr-y the undoes or redoes the last changes to the text fields. Is their a way using JavaScript to effectively hijack the ctr-z and ctr-y keypress events that occur anywhere on the page and cause them to run my own functions. Or at a minimum to disable the standard browser functionality.

I need to get this working the recent versions of Firefox and Chrome on windows only.

2 Answers 2

4

Using jQuery:

$(document).keydown(function (keyEvent) {
   var keyCode = keyEvent.keyCode;
   if (keyEvent.metaKey === true || keyEvent.ctrlKey === true) {
      if (keyCode === 89) {
         //fire your custom redo logic
         keyEvent.preventDefault();
         return false;
      } 
      else if (keyCode === 90) {
         //special case (CTRL-SHIFT-Z) does a redo (on a mac for example)
         if (keyEvent.shiftKey === true) {
            //fire your custom redo logic
         }
         else {
            //fire your custom undo logic
         }
         keyEvent.preventDefault();
         return false;
      }
   } 
});

This should handle all keyboard based events. It will not handle what happens if the user clicks undo in the menu bar or right clicks and selects undo.

Sign up to request clarification or add additional context in comments.

Comments

0

you may put on your page hidden textarea, bind onclick mouse event to function, which will set focus to the textarea, bind the keyboard events of this textarea and if an event is keydown and key is z or y and modifyer is ctrl - then invoke your redo/undo action.

2 Comments

How do I determine if the modifier is ctrl.
w3schools.com/jsref/event_ctrlkey.asp function isKeyPressed(event) { if (event.ctrlKey==1) { // "The CTRL key was pressed!" } ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.