Our Blog

Let us find tech solutions together

Nov 26

Integrating mousetrap.js with Wicket

By kinabalu | Comments

 

Over the weekend, I came across a neat library mousetrap.js used to add key commands to your web application. It can be used in any browser including:

  • Internet Explorer 6+ (wow)
  • Chrome
  • Safari
  • Firefox
  • Opera (yay Belarus!)

Basically the way it works, is

  1. add the Javascript library to the page
  2. start binding commands

[javascript] Mousetrap.bind(‘command+k’, function(e) { _someFunctionality(); }); [/javascript]

Here’s an example of usage in the Mystic Paste code. We’re adding an AbstractDefaultAjaxBehavior that we’re passing to Mousetrap and binding the key combination of pressing an ‘n’ to move the user to the New Paste page. Within the pastebin, we have the following key commands right now:

  • n - new paste
  • h - history page
    • left arrow - previous page
    • right arrow - next page
    • shift+left arrow - first page
    • shift+right arrow - last page

And here’s a snippet of usage: [java] final AbstractDefaultAjaxBehavior historyNav = new AbstractDefaultAjaxBehavior() { @Override protected void respond(AjaxRequestTarget target) { throw new RestartResponseException(HistoryPage.class); } }; add(historyNav);

mousetrap.addBind(new KeyBinding().addKeyCombo("h"), historyNav); [/java]

We’ve also done the work of setting up a Maven repository for the library to easily add it to your Wicket code:

[xml] <repository> <id>mystic-mvn-repo</id> <name>Mystic Github Maven Repository</name> <url>https://raw.github.com/kinabalu/mystic-mvn-repo/master/snapshots</url> </repository> … <dependency> <groupId>com.mysticcoders</groupId> <artifactId>wicket-mousetrap</artifactId> <version>0.1-SNAPSHOT</version> </dependency> [/xml]

If you’d like to grab it manually to integrate with your code, or just peruse the source you can find it on Github wicket-mousetrap.