jQuery Gestures
I'm still working on the redesign, but from time to time I like to take a break and work on a one night project. Today's project was inspired by this article. Although I loved the idea, I found it lacked several things :
- Visual feedback : you have no idea of the mouse gesture you've just done;
- Customization : adding a gesture isn't obvious;
- Complex gestures : you can't have sequences, such as
Up, Left, Up, Right, Down
I rewrote the code, using jQuery, and added those missing features. In order to provide visual feedback, I use a canvas element which is displayed above the content (and can be enabled and disabled) and I simply draw lines on it.
The sequences of gestures are dealt with using a stack on which moves are pushed1, if two identical moves follow each other (such as Right, Right) only the first one is taken into account.
The last part is customization, complex gestures are recorded as simple strings containing the characters U,D,L,R, and each string is associated to a function.
You can play with the demo, download the plugin and look at the example below.
$.gestures.init({active:false,color:'#ff0000'});
// adds a new gesture : Down
$.gestures.register('D', function() {
alert('down !');
});
// a more complex gesture : Down, Left, Up, Right
$.gestures.register('DLUR', function() {
alert('this is a rectangle, no ?');
});
// you can log unknown gestures :
$.gestures.error(function(gesture) {
alert("oops, I don't understand what \""+gesture+"\" means");
});
// useful keyboard tricks :
$(window).keydown(function(e) {
if ($.gestures.active() && e.which==27) {
// disable capture when user presses ESC
$.gestures.disable();
} else if (!$.gestures.active() && e.which==17) {
// enable capture when CTRL is pressed
$.gestures.enable();
}
});
$(window).keyup(function(e) {
// disable capture when CTRL is not pressed
if ($.gestures.active() && e.which==17) {
$.gestures.disable();
}
});
I just have FF3 installed on this machine, so I haven't been able to test this on other browsers. I suppose it should work on Opera, Safari and Chrome, and not on IE (unsupported canvas). Anyway, if it doesn't, feel free to hack the code, or leave a comment
- A move is an atomic gesture, it can be
Up,Down,LeftorRight[↩]
