Vishesh Joshi
Vishesh Joshi

Reputation: 1611

Prevent keypress to bubble to input in mousetrap

I am using mousetrap for capturing key presses. One of the shortcuts I want to define is to focus on an input.

Mousetrap.bind('i', function() { $('.input').focus() });

The focussing works fine, but the 'i' keypress also gets bubbled to the input, and with being focussed, the input also gets populated with 'i'.

Is there a way to prevent the 'i' from being written in the input? Any help is appreciated.

Thanks

Upvotes: 0

Views: 1002

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

Right there in the documentation:

As a convenience you can also return false in your callback:

Mousetrap.bind(['ctrl+s', 'meta+s'], function(e) {
    _saveDraft();
    return false;
});

Returning false here works the same way as jQuery's return false. It prevents the default action and stops the event from bubbling up.

So:

Mousetrap.bind('i', function() {
    $('.input').focus();
    return false;
});

Upvotes: 3

Related Questions