2017년 6월 2일 금요일

file trigger


Could someone tell me if there is a function file trigger in app inventor ?
My requirement is to launch a certain action whenever a file is created (for example whenever a picture is taken)

--
you can use the 'when File GotText' trigger in combination with the clock

Set the Timer to an interval 
when Tmer fires try to read the file
if succsessful, the 'when File.GotText' fires (that is your trigger)
if not, you'll get an error message. To avoid this use the 'When ErrorOccured' block (can be empty or filled with action)

--
My requirement is to launch a certain action whenever a file is created (for example whenever a picture is taken)
use the Camera.AfterPicture event to launch your action

--
Great !

Thank you,

-- 
The camera.afterpicture event only works when starting the camera app from within the custom app itself ?
This would not work as a sort of background monitoring app ?

If I want to use the camera app provided by the manufacturer (huawei in this case) I get many options to improve image quality.
Let's say I take a picture directly from that app,
then would my own app kick in and do an afterpicture routine ?

-- 
app
yes

app
Let's say I take a picture directly from that app,
app
unfortunately not, because App Inventor apps can't run in the background
probably later this year we will get the services feature...

-- 
It's possible to take directory listings and compare them to one another,
to see what has changed.

Maybe you can make that work.

-- 
The solution Rudolph proposed seems to be the best one for now.
I'm also looking at automagic or tasker which has those functions build-in (file moved, changed, etc..) and a way to link those with AI2.

-- 

arctan calculation in app inventor



Dear members, I'm trying to make a program to calculate aperture angle, and I need arctan function like you can find on python, but theres no way to make it work with 1/tan function or whichever

Is it possible to do with app inventor?

--
what about using the atan block?

--
:D Thanks, I didnt see the block 

--

App inventor servives background notifications and tasks fail?


hello everyone i am working on a basic app the app will send message choosed time like alarm. i did that so but it is not working. 


--
this is a very early version and there is still a lot to do
it still might be too early to use this version to do some tests and to give feedback
maybe later this year we will get a better version of the services functionality


--

TextToSpeech Languages


What languages are available for TextToSpeech?  Are they all offline?

--
The language code: ...changes the pronounciation of words, not the actual language spoken.
The country code: ...can affect the pronounciation.
If I ask TextToSpeech to say words from another language, will it speak that language?

-- 
Never mind, I found the answer here:
YandexTranslator translation of text strings

-- 
Are the language codes the same codes that Yandex uses?  Table of Yandex languages and codes are here.

-- 
The language codes Yandex uses are different that what the TTS engine requires. 

Some language/country TTS codes are here: https://tech.yandex.com/translate/doc/dg/concepts/api-overview-docpage/ ; Search the Internet for more, there are plenty more languages TTS knows. The following may work:http://www.science.co.il/language/locale-codes.asp

-- 
Thank you!

-- 
How about the ISO 639-1: two-letter codes in the table on Wikepedia here?  I think those ones will work, too...

-- 
I tried to find the supported languages under Android developer documentation and searched the internet for TTS codes, but I cannot find a full list.  I want to make an app with a list of TTS languages to select from.  I'll be getting the available countries and languages with the TextToSpeech blocks, but how's the user supposed to know what the codes mean?  So I want to search a list of codes and names to get the names, so I can display the names instead.

Do you know of a list?  The only full-looking list I found was this one here, and I don't think it'll work.

-- 

Getting Yandex Language Codes


How do you get the list of languages and their codes for Yandex translate?  I cannot understand what this article here is instructing me to do.  How can I send ui=language code when I don't know the language code?

--
Take a look at country codes here: https://tech.yandex.com/translate/doc/dg/concepts/api-overview-docpage/
Next, take a look at my tutorial here: YandexTranslator translation of text strings

-- 
Most of us are speaking English, so the language code would be en, like in their example.

-- 
Awesome!  Thanks!

My app will offer as many languages as there are languages available.  Is there a way to get the languages and codes from Yandex Translate somehow so that if a new language is added the app offers that language, too?

-- 

acessing to WEB Database - How can I do it properly


I do a project, getting datas from my server to the App there processing the datas offline and syncronizing when online.

I followed http://puravidaapps.com/mysql.php

mysql.aia
mysql.php

And I looked at https://puravidaapps.com/filebyfile.php
FileByFile.aia
FileByFile_Drive.aia

I have a runQuery And I managed to get datas from my server. But with several problems:

1. I found, that when I open the app, the first call is not executed or answered. Nothing happens. I Do not know why.
2. Sometimes the call gave a empty result same call later or earlier gave a correct result.
3. Greatest problem is, that I have to wait for the result to go on with my programm. See:

Call from web for a list (Sending to runquery, waiting for Web1.response. Saving the data to tinydb.)
when list received go on and display the list. (getting from Tinydb and display)
This should work in one block. (except runquery and web1response)

And I looked at https://puravidaapps.com/filebyfile.php: It works, but by calling the next call after finishing the first. That might be a way.

I have allways the problem, that the Datas from the web are not allways filled properly to the tinyDB. Then I got an empty Item and an error message.  I think because auf time problems.

So how can I let wait the block for the result?
Is there a solution or explication for exchanging datas from WEB Database and TinyDB.

Note. The app should work without regular Internet and with slow connection!

--
Have you seen the Waiting and Timing section of this FAQ?

If that doesn't help, post your relevant blocks images here.

-- 

And I looked at https://puravidaapps.com/filebyfile.php: It works, but by calling the next call after finishing the first. That might be a way.

exactly this you have to do if you work with asynchronous methods

-- 

[App Inventor Open Source Development] Re: Disabling the hardware menu button


First of all: I am no coder and posting something in an Open Source group means that i actualy don't know what i am doing ;-)
But i am good at googling and digging through things. In manipulating some WordPress stuff this way i had good outcomes.
But this is the first time that i looked behind the scenes of an android app. I am posting here, because i would like to share what i have done with the open source community. I guess others have simular wishes and maybe better guys can extend this to add new features. Additionaly i would like to see you "pros" commenting on this. I do have only one test device (Galaxy S4, 4.4.2) and on my device it works. But i have no clue about other phones and i have no clue if this can lead to unexpected errors or hurting something else, so please give me your opinions.

So, what was my intend?
I realy don't like the behaviour of the AI2 apps when the hardware menu button is clicked. It is not about the "Invented by MIT" part (which can be out-commented anyway), but the total thing. It is ugly and doesn't go with android design guidelines. It holds only two objects, while my app has another menu with around 10 objects and i think it is stupid to have two different menus in one app. And it is not translateable, so my app is in a total different language than the hardware menu is. My wish would be to set the hardware menu button to something like ListPicker1 for example. But as i have no clue how to do it, i focused on just disabling the hardware button. I prefer to have this button rather dead than having two different menus and not being able to influence one of them.

What have i done?
Based on a post in this thread (The new About Screen property in AI2 Version nb122) i decompiled my apk with apktool, went to "your_project_name.apk\smali\com\google\appinventor\components\runtime\form.smali" and deleted this whole part of code:




.method public onCreateOptionsMenu(Landroid/view/Menu;)Z
    .locals 1
    .param p1, "menu"    # Landroid/view/Menu;

    .prologue
    .line 1365
    invoke-super {p0, p1}, Landroid/app/Activity;->onCreateOptionsMenu(Landroid/view/Menu;)Z

    .line 1368
    invoke-virtual {p0, p1}, Lcom/google/appinventor/components/runtime/Form;->addExitButtonToMenu(Landroid/view/Menu;)V

    .line 1369
    invoke-virtual {p0, p1}, Lcom/google/appinventor/components/runtime/Form;->addAboutInfoToMenu(Landroid/view/Menu;)V

    .line 1370
    const/4 v0, 0x1

    return v0.end method

After that i recompiled using apktool, zipped it, copied the classes.dex out of the zip, decompiled the original apk with app2market, deleted the classes.dex from the original, added the one i got out of the modified smali, recompiled and signed the app with app2market.

On my phone this apk does now what i want: i does nothing when hitting the hardware menu button.

Pls give me your thoughts on this.

--
if you are partial to customising AI, I would suggest you get a local
server running; it might take you a while but you seem to be used to
do some sysadmin with wordpress and such.

Instead of having to do that in each of your apps, you can delete
those menus from the original code. The lines to delete start here:
https://github.com/mit-cml/appinventor-sources/blob/master/appinventor/components/src/com/google/appinventor/components/runtime/Form.java#L1362

You will see that it's quite similar in structure to the lines you
deleted in the de-compiled app. After deleting or commenting out those
lines, and compiling the server again (you'll need to learn how to do
this), you run your custom server locally on your machine, and can
create your own apps with no menu options (no need to hack the apk).

The main document (and it's a long one!) to get your server up and
running locally can be found here:
How to build App Inventor from the MIT sources

--
This is interesting. Could you do a tutorial or something on how you did this step?

"decompiled my apk with apktool, went to "your_project_name.apk∖smali∖com∖google∖appinventor∖components∖runtime∖form.smali" "
--
This is interesting. Could you do a tutorial or something on how you did this step?
"decompiled my apk with apktool, went to "your_project_name.apk\smali\com\google\appinventor\components\runtime\form.smali" "
see here https://puravidaapps.com/packagename.php


--
Hi Tony,  Thanks so much for the info. I only want to remove the "invented by MIT" part, can you  please tell me how it's done?

-- 
I only want to remove the "invented by MIT" part
see here https://puravidaapps.com/about.php

PS: a better place to ask this question would have been the main forum https://groups.google.com/forum/#!forum/mitappinventortest

--
Thank you Sir. Will do that for next time.

--
Hey Jos I have the server running. and still have the archive from the download.
do you have a link to how to decompile the AI2U and remove or modify the hardware menu?  I know about the block method with <1-- can apk decompiler work with notepad++?

--
Hi there, I really know nothing about AI2U; do they have a forum or something?

--
Can you make a video dude on how to do it exactly it would help us a lot.Thanks!!!!

--

information


Hi, I can not go from where you can not download the app on iphone, so it's downloaded to pc, but opening the link i do not understand anything! If you can kindly explain how to do it, thank you very much. 

--
App Inventor can only create apps for Android. Unfortunately Apple devices are not supported.

-- 
Watch  thunkable.com  for that.

-- 

bluetooth status not updating from connected to not connected


I am trying to make a bluetooth based app in which I have used a label to show the status of connection....whether connected or not connected.
Initially no device is connected...so the label shows NOT CONNECTED, when a connection is established it changes to CONNECTED but when the connection is lost again it doesn't change to NOT CONNECTED. I have used a clock timer to check whether the bt device is connected or not, as done in most of the videos available online for this purpose.
Please help.

--
Can you post your blocks? I am wondering about this...

-- 
but when the connection is lost again it doesn't change to NOT CONNECTED.

yes, that's correct, that's how bluetooth works
you will have to send something to find out, if the connection is lost: you will get an error then
  Error 516: Unable to write: Connection reset by peer
see also https://puravidaapps.com/btchat.php
btchat.aia

Known Issues
  • While trying to connect, both client and server display an "Error 509 Accept Connection: Unable to accept a connection from a bluetooth device". This message can be ignored.
  • As far as I can see, after client or server disconnected, there is no possibility for the chat partner to see, that the connection is gone. Therefore currently an "Error 516: Unable to write: Connection reset by peer" will be diplayed after trying to send a text without connection.
  • Sometimes "Error 507: Unable to connect. Is the device turned on?" shows up while trying to connect.
--
I am new to this forum can u tell me how to add code blocks here
or i just have to write the logic?

-- 

-- 

Bluetooth error 507


Hello im trying to connect my app with my bluetooth device ( simblee DIP(rfduino)) and when i click on choose bluetooth i can see my simblee on the black list so it works fine but when i click on it to connect it just says error 507 and is the device turned on? which it clearly is. help appreciated!

--
Nvm case closed, looked around with the BLE extension and i got a connection so it worked!

--
My Google exercise informs me that the Simblee DIP is a Bluetooth 4.0 Low Energy device, therefore you will need to use the BLE extension to connect.
Look here: MIT App Inventor Extensions

--
.

Is it possible to post comments or document the code in the inventor app


Write a doc with screen print pictures.

Attach comment bubbles to your blocks in the Blocks Editor.
(See attached.)
-- 

Fingerprint Sensor in MIT app inventor


Can I interface finger print sensor to app while creating app in MIT app inventor?

-- 
unfortunately the latest API Level we currently can use is API Level 22 = Android 5.1.1.
So all features, which have been introduced later are currently not possible.


--

Doc for Hammer.js

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!
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 tapdoubletappresshorizontal 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.
Lots of love to Eight Media for making this project possible and open source.

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.
BrowserPanPinchPressRotateSwipeTapMulti-userTouch-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/ mousen/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 penn/a
Windows 8 /w touchn/a
Windows 8 /w mousen/a
Windows 8 /w mixedn/a
Examples

Changelog

2.0.8, 2016-04-22

Manager
Input
  • Fixed de-duping of mouse events on mouse touch combo devices (#917#863bfeb89a)
Touch-action
  • Added support map for specific values of touch-action (#952fbe9fd7)

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. (#754439c7a6)
  • 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 (#768da49a27)
  • 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 (#728605bd3b)
  • Fixed dependency on non standard touch list ordering (#610#791287720a)
  • Fixed swipe to not trigger after multitouch gesture (#640711d8a1)
  • 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 (#82492f2d76)
  • Fixed leaking options between recognizer instances (#813af32c9b)
  • 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 tapdoubletappanswipepresspinch 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 computeautopan-ypan-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 tapdoubletappresshorizontal 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 getmethod, it returns the added Recognizer instance. The get and removemethods 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

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.
NameValue
typeName of the event. Like panstart.
deltaXMovement of the X axis.
deltaYMovement of the Y axis.
deltaTimeTotal time in ms since the first input.
distanceDistance moved.
angleAngle moved.
velocityXVelocity on the X axis, in px/ms.
velocityYVelocity on the Y axis, in px/ms
velocityHighest velocityX/Y value.
directionDirection moved. Matches the DIRECTION constants.
offsetDirectionDirection moved from it’s starting point. Matches the DIRECTION constants.
scaleScaling that has been done when multi-touch. 1 on a single touch.
rotationRotation (in deg) that has been done when multi-touch. 0 on a single touch.
centerCenter position for multi-touch, or just the single pointer.
srcEventSource event object, type TouchEventMouseEvent or PointerEvent.
targetTarget that received the event.
pointerTypePrimary pointer type, could be touchmousepen or kinect.
eventTypeEvent type, matches the INPUT constants.
isFirsttrue when the first input.
isFinaltrue when the final (last) input.
pointersArray with all pointers, including the ended pointers (touchendmouseup).
changedPointersArray with all new/moved/lost pointers.
preventDefaultReference 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.
NameValue
DIRECTION_NONE1
DIRECTION_LEFT2
DIRECTION_RIGHT4
DIRECTION_UP8
DIRECTION_DOWN16
DIRECTION_HORIZONTAL6
DIRECTION_VERTICAL24
DIRECTION_ALL30

Input Events

Hammer maps all types of input (mousedown, mousemove, touchmove, pointercancel) to these constants.
NameValue
INPUT_START1
INPUT_MOVE2
INPUT_END4
INPUT_CANCEL8

Recognizer States

Used internally by the recognizers to define its state.
NameValue
STATE_POSSIBLE1
STATE_BEGAN2
STATE_CHANGED4
STATE_ENDED8
STATE_RECOGNIZEDSTATE_ENDED
STATE_CANCELLED16
STATE_FAILED32

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-actionproperty. 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 preventDefaultmanually 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…
GestureLeast restrictive touch-action value
pressauto
tapauto
multitapmanipulation
vertical pan/swipepan-x
horizontal pan/swipepan-y
rotatepan-x pan-y
pinchpan-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.
OptionDefaultDescription
eventpanName of the event.
pointers1Required pointers. 0 for all pointers.
threshold10Minimal pan distance required before recognizing.
directionDIRECTION_ALLDirection 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).
OptionDefaultDescription
eventpinchName of the event.
pointers2Required pointers, with a minimal of 2.
threshold0Minimal 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.
OptionDefaultDescription
eventpressName of the event.
pointers1Required pointers.
threshold9Minimal movement that is allowed while pressing.
time251Minimal press time in ms.

Events

  • press
  • pressup
Hammer.Rotate(options)
Recognized when two or more pointer are moving in a circular motion.
OptionDefaultDescription
eventrotateName of the event.
pointers2Required pointers, with a minimal of 2.
threshold0Minimal 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.
OptionDefaultDescription
eventswipeName of the event.
pointers1Required pointers.
threshold10Minimal distance required before recognizing.
directionDIRECTION_ALLDirection of the panning.
velocity0.3Minimal 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
OptionDefaultDescription
eventtapName of the event.
pointers1Required pointers.
taps1Amount of taps required.
interval300Maximum time in ms between multiple taps.
time250Maximum press time in ms.
threshold2While doing a tap some small movement is allowed.
posThreshold10The 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 touchstarttouchmove 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 mousedownmousemove 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:mousedownmouseentermouseleavemousemovemouseoutmouseover 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
  • 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.