Getting Started
Hammer is a open-source library that can recognize gestures made by touch, mouse and pointerEvents. It doesn’t have any dependencies, and it’s small, only 7.34 kB minified + gzipped!
- Minified code (v2.0.8)
- Uncompressed code (v2.0.8)
- Changelog
- Browse the source on GitHub
- Looking for the 1.1 version? You can find it here.
What’s new in 2.0?
It’s completely rewritten, with reusable gesture recognizers, and improved support for the recent mobile browsers by making use of the touch-action css property when possible. Also support for multiple Hammer instances at the same time, so multi-touch becomes possible.
Usage
It’s easy to use, just include the library and create a new instance.
var hammertime = new Hammer(myElement, myOptions);
hammertime.on('pan', function(ev) {
console.log(ev);
});
By default it adds a set of
tap
, doubletap
, press
, horizontal pan
and swipe
, and the multi-touch pinch
and rotate
recognizers. The pinch and rotate recognizers are disabled by default because they would make the element blocking, but you can enable them by calling:hammertime.get('pinch').set({ enable: true });
hammertime.get('rotate').set({ enable: true });
Enabling vertical or all directions for the
pan
and swipe
recognizers:hammertime.get('pan').set({ direction: Hammer.DIRECTION_ALL });
hammertime.get('swipe').set({ direction: Hammer.DIRECTION_VERTICAL });
Also the viewport meta tag is recommended, it gives more control back to the webpage by disabling the doubletap/pinch zoom. More recent browsers that support the touch-action property don’t require this.
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">
More control
You can setup your own set of recognizers for your instance. This requires a bit more code, but it gives you more control about the gestures that are being recognized.
var mc = new Hammer.Manager(myElement, myOptions);
mc.add( new Hammer.Pan({ direction: Hammer.DIRECTION_ALL, threshold: 0 }) );
mc.add( new Hammer.Tap({ event: 'quadrupletap', taps: 4 }) );
mc.on("pan", handlePan);
mc.on("quadrupletap", handleTaps);
The example above creates an instance containing a
pan
and a quadrupletap
gesture. The recognizer instances you create are being executed in the order they are added, and only one can be recognized at the time.
See the pages about the
recognizeWith
and requireFailure
for more details.Notes
Built by Jorik Tangelder. It’s recommended to listen to this loop while using hammer.js. Follow @jorikdelaporik for some tweets about this library.
Tips ‘n Tricks
Event delegation and DOM events
Hammer is able to trigger DOM events with the option
domEvents: true
. This will give your methods like stopPropagation()
, so you can use event delegation. Hammer will not unbind the bound events.Try to avoid vertical pan/swipe
Vertical panning is used to scroll your page, and some (older) browsers don’t send events so Hammer isn’t able to recognize these gestures. An option would be to provide an alternative way to do the same action.
Test on a real device
Sometimes Hammer just needs some fine-tuning, like the swipe velocity or some other thresholds. Also, for better performance on slower devices your should try to keep you callbacks as simple as possible. Sites like JankFree.org have articles about how to improve the performance.
Remove tap highlight on Windows Phone
IE10 and IE11 on Windows Phone have a small tap highlight when you tap an element. Adding this meta tag removes this.
<meta name="msapplication-tap-highlight" content="no" />
“I can’t select my text anymore!”
Hammer is setting a property to improve the UX of the panning on desktop. Regularly, the desktop browser would select the text while you drag over the page. The
user-select
css property disables this.
If you care about the text-selection and not so much about the desktop experience, you can simply remove this option from the defaults. Make sure you do this before creating an instance.
delete Hammer.defaults.cssProps.userSelect;
“After a tap, also a click is being triggered, I don’t want that!”
That click event is also being called a ‘ghost click’. I’ve created a small function to prevent clicks after a touchend. It is heavily inspired from this article from Ryan Fioravanti.
Browser/device support
Don’t worry if your browser or OS isn’t listed, it might work anyway! Internet Explorer 8 and older aren’t supported.
Browsers that have native support for touch-action might have an improved experience then the browsers that don’t. See the touch-action page for more details.
Browser | Pan | Pinch | Press | Rotate | Swipe | Tap | Multi-user | Touch-action |
---|---|---|---|---|---|---|---|---|
Windows Phone 8 - IE10 | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ |
Android 2.3 - browser | ♥ | ♥ | ♥ | ♥ | ||||
Android 2.3 - FireFox | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | |
Android 4.x - browser | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | |
Android 4.4 - browser | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ |
Android 4 - Chrome | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ |
Android 4 - Opera | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ? |
Android 4 - FireFox | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | |
Android 4 w/ mouse | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | n/a |
iOS 6 | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | |
iOS 7 | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | |
iOS 8 | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | |
BlackBerry 10 | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ? | ? |
FireFox OS (simulator) | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ? | ? |
Desktop - IE11 | ♥ | ♥ | ♥ | ♥ | ♥ | |||
Desktop - IE10 | ♥ | ♥ | ♥ | ♥ | ♥ | |||
Desktop - IE9 | ♥ | ♥ | ♥ | ♥ | ||||
Desktop - Chrome | ♥ | ♥ | ♥ | ♥ | ♥ | |||
Desktop - Firefox | ♥ | ♥ | ♥ | ♥ | ||||
Desktop - Opera | ♥ | ♥ | ♥ | ♥ | ? | |||
Chromebook | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ? |
Windows 8 /w pen | ♥ | ♥ | ♥ | ♥ | ♥ | n/a | ||
Windows 8 /w touch | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | n/a |
Windows 8 /w mouse | ♥ | ♥ | ♥ | ♥ | ♥ | n/a | ||
Windows 8 /w mixed | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | ♥ | n/a |
Examples
Some example implementations to get you started.
- Basic implementation
- Basic with vertical Pan recognizer
- RecognizeWith with Pinch and Rotate
- RecognizeWith with a Quadrupletap recognizer
- SingleTap and DoubleTap (with recognizeWith/requireFailure)
- Nested pan/swipe recognizers
More example code can be found at the
/tests
directory at the repositoryChangelog
2.0.8, 2016-04-22
Manager
- Added check to ensure that the required parameters are present (#908, 085d3a8)
- Fixed restoration of Hammer.defaults.cssProps on destroy (#904theregttr5ki, 7d0e60f)
Input
Touch-action
2.0.6, 2015-12-23
- Add Assign method and deprecate merge and extend (#895fc01eae)
- Expose Hammer on window or self if either is defined to avoid issues when AMD is present but not used. ( 356f795)
- Add support for PointerEvent instead of MSPointerEvent if supported. (#754, 439c7a6)
- Fixed moz-prefix, prefix should be Moz not moz. (3ea47f3)
- Removed non-existent recognizer (f1c2d3b)
- Fixed config leaking between instances(189098f)
- Fixed gaps in gesture configs and update tests to match (70c2902)
- Fixed Manager off method (#768, da49a27)
- Added compatibility with requirejs optimizer namespaces ( 70075f2)
- Made touchaction test zoomable ( 50264a7)
- Fixed preventing default when for
pan-x pan-y
case ( 95eaafa) - Fixed incorrect touch action pan direction ( a81da57)
- Fixed combined pan-x pan-y to resolve to none ( fdae07b)
- Fixed inverted touch-action for pan recognizer (#728, 605bd3b)
- Fixed dependency on non standard touch list ordering (#610, #791, 287720a)
- Fixed swipe to not trigger after multitouch gesture (#640, 711d8a1)
- Fixed swipe recognizer to use overall gesture direction and velocity ( 963fe69)
- Fixed getDirection returning reversed direction ( e40dcde)
- Fixed detection of tap when multi touch gestures are present ( c46cbba)
- Fixed incorrect event order (#824, 92f2d76)
- Fixed leaking options between recognizer instances (#813, af32c9b)
- Fixed detection when element has no style attribute ( 5ca6d8c)
2.0.4, 2014-09-28
- Fix IE pointer issue. #665
- Fix multi-touch at different elements. #668
- Added experimental single-user Touch input handler. This to improve performance/ux when only a single user has to be supported. Plans are to release 2.1 with this as default, and a settings to enable the multi-user handler.
2.0.3, 2014-09-10
- Manager.set improvements.
- Fix requireFailure() call in Manager.options.recognizers.
- Make DIRECTION_ALL for pan and swipe gestures less blocking.
- Fix Swipe recognizer threshold option.
- Expose the Input classes.
- Added the option
inputClass
to set the used input handler.
2.0.2, 2014-07-26
- Improved mouse and pointer-events input, now able to move outside the window.
- Added the export name (
Hammer
) as an argument to the wrapper. - Add the option experimental
inputTarget
to change the element that receives the events. - Improved performance when only one touch being active.
- Fixed the jumping deltaXY bug when going from single to multi-touch.
- Improved velocity calculations.
2.0.1, 2014-07-15
- Fix issue when no document.body is available
- Added pressup event for the press recognizer
- Removed alternative for Object.create
2.0.0, 2014-07-11
- Full rewrite of the library.
General API
- Hammer
- Hammer.defaults
- Hammer.Manager
- Hammer.Recognizer
- Hammer.input event
- Event object
- Constants
- Utils
Hammer
Creates a Manager instance with a default set of recognizers and returns the manager instance. The default set contains
tap
, doubletap
, pan
, swipe
, press
, pinch
and rotate
recognizer instances.
You should only use this when you’re fine with the default setup, or have set your own initial setup.
Constructor(HTMLElement, [options])
Just your element, and options. the options will be merged with Hammer.defaults. Also, the recognizer set as defined in
Hammer.defaults.preset
will be added.
If you’ll pass an empty
recognizer
option, no initial recognizers will be added.var myElement = document.getElementById('hitarea');
var mc = new Hammer(myElement);
Hammer.defaults
The defaults when creating an instance that are merged being with your options.
touchAction: ‘compute’
Accepts the
compute
, auto
, pan-y
, pan-x
and none
values. The default option will choose the correct value for you, based on the recognizers.domEvents: false
Let Hammer also fire DOM events. This is a bit slower, so disabled by default. Recommended to set to
true
if you want to play with event delegation.enable: true
Accepts a boolean, or a function that should return a boolean which is.
cssProps: {….}
A collection of css properties that improve the handling of the input events. For details take a look at the JSDoc.
preset: [….]
Default recognizer setup when calling
Hammer()
. When creating a new Manager these will be skipped.
By default it adds a set of
tap
, doubletap
, press
, horizontal pan
and swipe
, and the multi-touch pinch
and rotate
recognizers. The pinch and rotate recognizers are disabled by default because they would make the element blocking.Hammer.Manager
The Manager is the container of all the recognizer instances for your element. It sets up the input event listeners, and sets the touch-action property for you on the element.
constructor(HTMLElement, [options])
Just your element, and options. the options will be merged with Hammer.defaults.
var mc = new Hammer.Manager(myElement);
You can setup an initial recognizer set with the option
recognizers
. The Array should be structured like this;var mc = new Hammer.Manager(myElement, {
recognizers: [
// RecognizerClass, [options], [recognizeWith, ...], [requireFailure, ...]
[Hammer.Rotate],
[Hammer.Pinch, { enable: false }, ['rotate']],
[Hammer.Swipe,{ direction: Hammer.DIRECTION_HORIZONTAL }],
]
});
set(options)
Change an option on the manager instance. Using this method is recommended, because it will update the
touchAction
value if needed.mc.set({ enable: true });
get(string), add(Recognizer) and remove(Recognizer)
Add a new
Recognizer
instance to the Manager. The order of adding is also the order of the recognizers being executed. Just like the get
method, it returns the added Recognizer
instance. The get
and remove
methods takes the event name (from a recognizer) or a recognizer instance as an argument.
Add and remove also accept an array of recognizers.
// both return instance of myPinchRecognizer
mc.get('pinch');
mc.get(myPinchRecognizer);
mc.add(myPinchRecognizer); // returns the recognizer
mc.add([mySecondRecogizner, myThirdRecognizer]);
mc.remove(myPinchRecognizer);
mc.remove('rotate');
mc.remove([myPinchRecognizer, 'rotate']);
on(events, handler) and .off(events, [handler])
Listen to events triggered by the added recognizers, or remove the binded events. Accepts multiple events seperated by a space.
mc.on("pinch", function(ev) {
console.log(ev.scale);
});
stop([force])
Stop recognizing for the current input session. When forced, the recognizer cycle is stopped immediately.
destroy()
Unbinds all events and input events and makes the manager unusable. It does NOT unbind any domEvent listeners.
Hammer.Recognizer
Every Recognizer extends from this class. All recognizers also have the option
enable
, which is a boolean value or a callback function to enable/disable the recognizer on the fly.constructor([options])
Just set the options.
var pinch = new Hammer.Pinch();
mc.add(pinch); // add it to the Manager instance
set(options)
Change an option on the recognizer instance. Using this method is recommended, because it will update the
touchAction
value if needed.recognizeWith(otherRecognizer) and dropRecognizeWith(otherRecognizer)
Run the recognizer simultaneous with the given other recognizer, in both directions. This is usable for like combining a pan with a swipe at the end, or a pinch with the ability to rotate the target as well. Dropping the connection only removes the link on the recognizer, not on the other recognizer. Both accept an array of recognizers.
If the recognizer is added to a manager, then this method also accepts the other recognizer’s event name as a string.
requireFailure(otherRecognizer) and dropRequireFailure(otherRecognizer)
Run the recognizer only when the other recognizer fails. Dropping the connection only removes the link on the recognizer, not on the other recognizer. Both accept an array of recognizers.
If the recognizer is added to a manager, then this method also accepts the other recognizer’s event name as a string.
Hammer.input event
A secret event is being triggered by Hammer,
hammer.input
. It is being emitted on every input that is being received, and enabled you to things with the raw input. Small, but powerful feature.hammertime.on("hammer.input", function(ev) {
console.log(ev.pointers);
});
Event object
All events that Hammer triggers all receive an event object containing the following properties.
Name | Value |
---|---|
type | Name of the event. Like panstart . |
deltaX | Movement of the X axis. |
deltaY | Movement of the Y axis. |
deltaTime | Total time in ms since the first input. |
distance | Distance moved. |
angle | Angle moved. |
velocityX | Velocity on the X axis, in px/ms. |
velocityY | Velocity on the Y axis, in px/ms |
velocity | Highest velocityX/Y value. |
direction | Direction moved. Matches the DIRECTION constants. |
offsetDirection | Direction moved from it’s starting point. Matches the DIRECTION constants. |
scale | Scaling that has been done when multi-touch. 1 on a single touch. |
rotation | Rotation (in deg) that has been done when multi-touch. 0 on a single touch. |
center | Center position for multi-touch, or just the single pointer. |
srcEvent | Source event object, type TouchEvent , MouseEvent or PointerEvent . |
target | Target that received the event. |
pointerType | Primary pointer type, could be touch , mouse , pen or kinect . |
eventType | Event type, matches the INPUT constants. |
isFirst | true when the first input. |
isFinal | true when the final (last) input. |
pointers | Array with all pointers, including the ended pointers (touchend , mouseup ). |
changedPointers | Array with all new/moved/lost pointers. |
preventDefault | Reference to the srcEvent.preventDefault() method. Only for experts! |
Constants
All constants are defined at the
Hammer
object. Since it are binary flags, you can use bitwise operators on it. MDN has some excellentdocumentation about this.Directions
Used for setting the direction of a recognizer, and for reading the value of an event.
Name | Value |
---|---|
DIRECTION_NONE | 1 |
DIRECTION_LEFT | 2 |
DIRECTION_RIGHT | 4 |
DIRECTION_UP | 8 |
DIRECTION_DOWN | 16 |
DIRECTION_HORIZONTAL | 6 |
DIRECTION_VERTICAL | 24 |
DIRECTION_ALL | 30 |
Input Events
Hammer maps all types of input (mousedown, mousemove, touchmove, pointercancel) to these constants.
Name | Value |
---|---|
INPUT_START | 1 |
INPUT_MOVE | 2 |
INPUT_END | 4 |
INPUT_CANCEL | 8 |
Recognizer States
Used internally by the recognizers to define its state.
Name | Value |
---|---|
STATE_POSSIBLE | 1 |
STATE_BEGAN | 2 |
STATE_CHANGED | 4 |
STATE_ENDED | 8 |
STATE_RECOGNIZED | STATE_ENDED |
STATE_CANCELLED | 16 |
STATE_FAILED | 32 |
Utils
Hammer.on(element, types, handler)
Wrapper around
addEventListener
that accepts multiple event types.Hammer.on(window, "load resize scroll", function(ev) {
console.log(ev.type);
});
Hammer.off(element, types, handler)
Like
Hammer.on
, this is a wrapper around removeEventListener
that accepts multiple event types.Hammer.each(obj, handler)
Iterate an array or an object’s own properties.
Hammer.each([10,20,30,40], function(item, index, src) { });
Hammer.each({a:10, b:20, c:30}, function(item, key, src) { });
Hammer.merge(obj1, obj2)
Merge properties from obj2 into obj1. Properties won’t be overwritten.
var options = {
b: false
};
var defaults = {
a: true,
b: true,
c: [1,2,3]
};
Hammer.merge(options, defaults);
// options.a == true
// options.b == false
// options.c == [1,2,3]
Hammer.extend(obj1, obj2)
Extend obj1 with the properties from obj2. Properties will be overwritten.
var obj1 = {
a: true,
b: false,
c: [1,2,3]
};
var obj2 = {
b: true,
c: [4,5,6]
};
Hammer.extend(obj1, obj2);
// obj1.a == true
// obj1.b == true
// obj1.c == [4,5,6]
Hammer.inherit(child, base, [properties])
Simple class inheritance.
function Animal(name) {
this.name = name;
}
function Dog() {
Animal.apply(this, arguments);
}
Hammer.inherit(Dog, Animal, {
bark: function() {
alert(this.name);
}
});
var dog = new Dog('Spaikie');
dog.bark();
Hammer.bindFn(fn, scope)
Simple alternative for
Function.bind
.function myFunction(ev) {
console.log(this === myContext); // is true
}
var myContext = {
a: true,
b: false
};
window.addEventListener('load', Hammer.bindFn(myFunction, myContext), false);
Hammer.prefixed(obj, name)
Get the (prefixed) property from the browser.
Hammer.prefixed(document.body.style, 'userSelect');
// returns "webkitUserSelect" on Chrome 35
The Touch-action property
Chrome 35+, IE10+ and soon FireFox, support the touch-action
property. This property tells the browser how to handle touches on an element. It improves the detection and experience of the gestures a lot, because it can prevent scrolling of the page without any JavaScript has to be executed, which can be too late in some cases.
Hammer uses a javascript fallback for this property when needed, so it is working with non-supporting browsers too. Still, on some (unpopular) devices the fallback might not work as good as the native support.
By default it sets a value based on the recognizer settings. You can overwrite this by giving the option touchAction
to the Manager.
When you set the touchAction to auto
it doesn’t prevent any defaults, and Hammer would probably break. You have to call preventDefault
manually to fix this. You should only use this if you know what you’re doing.
Preferred touch-action values per gesture
If you do want to set your own value, then the table below should help you a bit…
Gesture Least restrictive touch-action value
press auto
tap auto
multitap manipulation
vertical pan/swipe pan-x
horizontal pan/swipe pan-y
rotate pan-x pan-y
pinch pan-x pan-y
Simultaneous recognizing
If you want to recognize two gestures simultaneously, you can use the the
recognizeWith()
method. The example below does this with the pinch and rotate recognizers, which will improve usability.var pinch = new Hammer.Pinch();
var rotate = new Hammer.Rotate();
pinch.recognizeWith(rotate);
Now Hammer is able to run pinch and rotate the same time. You can also separate them with the
dropRecognizeWith()
method on the recognizer instance.
Require failure of an other recognizer
With the method
requireFailure()
you can let a recognizer require the failure of an other recognizer before recognizing. This could become useful when you want to nest two gestures, like pan-horizontal and pan-vertical. Removing the dependency could be done with the dropRequireFailure()
method.var horizontal = new Hammer.Pan({
event: 'panh',
direction: Hammer.DIRECTION_HORIZONTAL
});
var vertical = new Hammer.Pan({
event: 'panv',
direction: Hammer.DIRECTION_VERTICAL
});
vertical.requireFailure(horizontal);
Using requireFailure to recognize multiple taps
Because multiple gestures can be recognized simultaneously and a gesture can be recognized based on the failure of other gestures. Multiple taps on the same element can be easily recognized on this way:
var hammer = new Hammer(el, {});
var singleTap = new Hammer.Tap({ event: 'singletap' });
var doubleTap = new Hammer.Tap({event: 'doubletap', taps: 2 });
var tripleTap = new Hammer.Tap({event: 'tripletap', taps: 3 });
hammer.add([tripleTap, doubleTap, singleTap]);
tripleTap.recognizeWith([doubleTap, singleTap]);
doubleTap.recognizeWith(singleTap);
doubleTap.requireFailure(tripleTap);
singleTap.requireFailure([tripleTap, doubleTap]);
When a tap gesture requires a failure to be recognized, its recognizer will wait a short period to check that the other gesture has been failed. In this case, you should not assume that its tap gesture event will be fired immediately.
Toggle recognizers at runtime
A gesture can be enabled/disabled based on its
enable
property which must setup through the set
call or its constructor parameter.hammer.get('tap').set({ enable: false });
//Then you could enable it again when necessary
hammer.get('tap').set({ enable: true });
Instead of toggling the
enable
property each time on your app, you could delegate this responsibility to a custom function which will be checked with each new incoming touch event to decide if the event can be dispatched to the recognizer or not. This feature provides support to build complex gesture scenarios based on App/UI logic.var view = View.extend({
state: 'ACTIVE',
score: 0,
canRecognizeTap: function(recognizer, event) {
return this.state !== 'INACTIVE' && this.score > 0;
});
};
var mc = new Hammer.Manager(viewElement, {});
var canEnable = function(rec, input) {
return view.canRecognizeTap(rec, input);
}
mc.add(new Hammer.Tap({enable: canEnable}));
The
Manager.enable
option also works this way.
Hammer.Pan(options)
Recognized when the pointer is down and moved in the allowed direction.
Option | Default | Description |
---|---|---|
event | pan | Name of the event. |
pointers | 1 | Required pointers. 0 for all pointers. |
threshold | 10 | Minimal pan distance required before recognizing. |
direction | DIRECTION_ALL | Direction of the panning. |
Events
- pan, together with all of below
- panstart
- panmove
- panend
- pancancel
- panleft
- panright
- panup
- pandown
Notes
When calling
Hammer()
to create a simple instance, the pan and swipe recognizers are configured to only detect horizontal gestures.Hammer.Pinch(options)
Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
Option | Default | Description |
---|---|---|
event | pinch | Name of the event. |
pointers | 2 | Required pointers, with a minimal of 2. |
threshold | 0 | Minimal scale before recognizing. |
Events
- pinch, together with all of below
- pinchstart
- pinchmove
- pinchend
- pinchcancel
- pinchin
- pinchout
Notes
This recognizer is disabled by default because it would make the element blocking. You can enable it by calling:
javascript hammertime.get('pinch').set({ enable: true });
Hammer.Press(options)
Recognized when the pointer is down for x ms without any movement.
Option | Default | Description |
---|---|---|
event | press | Name of the event. |
pointers | 1 | Required pointers. |
threshold | 9 | Minimal movement that is allowed while pressing. |
time | 251 | Minimal press time in ms. |
Events
- press
- pressup
Hammer.Rotate(options)
Recognized when two or more pointer are moving in a circular motion.
Option | Default | Description |
---|---|---|
event | rotate | Name of the event. |
pointers | 2 | Required pointers, with a minimal of 2. |
threshold | 0 | Minimal rotation before recognizing. |
Events
- rotate, together with all of below
- rotatestart
- rotatemove
- rotateend
- rotatecancel
Notes
This recognizer is disabled by default because it would make the element blocking. You can enable it by calling:
javascript hammertime.get('rotate').set({ enable: true });
Hammer.Swipe(options)
Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
Option | Default | Description |
---|---|---|
event | swipe | Name of the event. |
pointers | 1 | Required pointers. |
threshold | 10 | Minimal distance required before recognizing. |
direction | DIRECTION_ALL | Direction of the panning. |
velocity | 0.3 | Minimal velocity required before recognizing, unit is in px per ms. |
Events
- swipe, together with all of below
- swipeleft
- swiperight
- swipeup
- swipedown
Notes
When calling
Hammer()
to create a simple instance, the pan and swipe recognizers are configured to only detect horizontal gestures.
Hammer.Tap(options)
Recognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur between the given interval and position. The eventData from the emitted event contains the property
tapCount
, which contains the amount of multi-taps being recognized.
If an Tap recognizer has a failing requirement, it waits the interval time before emitting the event. This is because if you want to only trigger a doubletap, hammer needs to see if any other taps are coming in. Read more about requireFailure
Option | Default | Description |
---|---|---|
event | tap | Name of the event. |
pointers | 1 | Required pointers. |
taps | 1 | Amount of taps required. |
interval | 300 | Maximum time in ms between multiple taps. |
time | 250 | Maximum press time in ms. |
threshold | 2 | While doing a tap some small movement is allowed. |
posThreshold | 10 | The maximum position difference between multiple taps. |
Events
- tap
jQuery plugin
A small jQuery plugin is available, and is just a small wrapper around the
Hammer()
class. It also extends the Manager.emit
method by triggering jQuery events.$(element).hammer(options).bind("pan", myPanHandler);
The Hammer instance is stored at
$element.data("hammer")
.
Angular.js directive
An Angular.js directive has been made by Ryan Mullins, which allows you to easy integrate Hammer in your Angular.js based projects. You can find documentation at the project page on GitHub.
Emulate touch on a desktop
Hammer provides a debug tool to emulate touch support in the browser. It fires DOM touch events as specified by W3C. When pressing the
shift
key, you can also use multi-touch events like pinch and rotate. You can also use this in other projects without Hammer.js.How to use
Include the javascript file, and call the
TouchEmulator()
function before any other libraries that do something with the touch input. It will set some fake properties to spoof the touch detection of some libraries, and triggers touchstart
, touchmove
and touchend
events on the mouse target.<script src="touch-emulator.js"></script>
<script> TouchEmulator(); </script>
function log(ev) {
console.log(ev);
}
document.body.addEventListener('touchstart', log, false);
document.body.addEventListener('touchmove', log, false);
document.body.addEventListener('touchend', log, false);
Also, the script includes polyfills for
document.createTouch
and document.createTouchList
.How it works
It listens to the
mousedown
, mousemove
and mouseup
events, and translates them to touch events. If the mouseevent has the shiftKey
property to true
, it enables multi-touch.
The script also prevents the following mouse events on the page:
mousedown
, mouseenter
, mouseleave
, mousemove
, mouseout
, mouseover
and mouseup
.Web platform tests
The script has been tested with the w3c web platform tests and passes all tests, except these;
- assert_true: event is a TouchEvent event expected true got false
- We trigger an event of the type
Event
- We trigger an event of the type
- assert_equals: touch list is of type TouchList expected “[object TouchList]” but got “[object Array]”
- assert_equals: touch is of type Touch expected “[object Touch]” but got “[object Object]”
Bookmarklet
javascript:!function(a){var b=a.createElement("script");b.onload=function(){TouchEmulator()},b.src="//cdn.rawgit.com/hammerjs/touchemulator/0.0.2/touch-emulator.js",a.body.appendChild(b)}(document);
Download the script from the repo, or just run
bower install hammer-touchemulator
.
댓글 없음:
댓글 쓰기