I am using the Mousetrap javascript library and am wanting to capture input on a specific element.
The scenario is I have a textbox for username and password which KnockoutJS binds to then when a button is pressed an ajax request is made to login the user. Now as there is no form and its not a real button its an anchor that Jquery UI turns into a button I was wondering if there was some simple way to get mousetrap to bind to the element rather than at the document level.
So for example a normal mousetrap binding would be:
Mousetrap.bind('enter', function(event) { CallSomeAjaxMethod(); });
Now that will check for any enter key press on the page (outside of a textbox element) and then do something based on it. Now the problem is in this case I am wanting to be able to ONLY capture this event whenever it is carried out within the scope of a specific element.
So for example I would be wanting to do something likethis:
var element = document.getElementById("some-element");
Mousetrap.bind('enter', element, function(event) { CallSomeAjaxMethod(); });
or maybe more fluent like:
Mousetrap.bind('enter', function(event) { CallSomeAjaxMethod(); }).on(element);
Is there any way to do this? the only way I can see to do it (with Mousetrap) currently is to have this document scope binding and just try to get the element the event was raised on if it is possible.
I know you can do this sort of thing with Jquery or vanilla js however as I already have Mousetrap loaded I would like to re-use it here if possible.
I wanted to follow up on this. As of version 1.5.0 (released today), this is now possible natively in Mousetrap.
For your specific example above all you have to do is
You can also create a new instance of mousetrap to bind multiple things.
Best of all it should be backwards compatible so all your existing code will still work.