hadf
hadf

Reputation: 282

How to override default browser undo action

I've implemeted an undo manager. The trouble is when the page contains an input text

<script>
    $(document).keypress(function(event) {
        switch (event.which) {
        case 26:
            if (event.shiftKey && event.ctrlKey) {
                // Ctrl+Shift+z
                redo();
            }
            else if (event.ctrlKey) {
                // Ctrl+z
                undo();
            }
            break;
        }
    })
</script>
<input type="text">

Then, when input text is edited, if I trigger an undo event by typing Ctrl+z, the input text is undone without my undo manager is called.

I would like to force the browser to call my undo manager on Ctrl+z, even when the page contains text field or text area.

Upvotes: 0

Views: 898

Answers (1)

skyline3000
skyline3000

Reputation: 7913

You need to listen to the keydown event rather than keypress. The browser undo triggers on keydown, but keypress doesn't occur until the key has been lifted up. Additionally, if you don't want the browser to do its own undo, you need to use event.preventDefault().

<script>
$(document).keydown(function(event) {
    switch (event.which) {
    case 90:
        if (event.shiftKey && event.ctrlKey) {
            // Ctrl+Shift+z
            event.preventDefault();
            redo();
        }
        else if (event.ctrlKey) {
            // Ctrl+z
            event.preventDefault();
            undo();
        }
        break;
    }
})
</script>

Upvotes: 1

Related Questions