Giter Site home page Giter Site logo

touchy's Introduction

Touchy

Touchy is a jQuery plugin for managing touch events on W3C-compliant browsers, such as Mobile Safari or Android Browser, or any browser that supports the ontouchstart, ontouchmove and ontouchend events.

It creates new custom events that a programmer may utilize at a high level, such as "touchy-pinch" and "touchy-rotate" among others, and thus avoid the low-level work of combining touch and gesture events to achieve these common gestural controls.

The minified file size is 9.43KB (2.69KB gzipped).

Log

  • April 11, 2013
    • Version 1.1
    • Added preventDefault options for the three phases: start, move, end.
    • Condensed the code a bit, shaving 0.05kb off the gzip size.
    • Fixed the wheel rotation examples, which had some bad CSS syntax in them.
  • August 8, 2012
    • Rotation velocity may now return negative values
  • August 3, 2012
    • Fixed backwards compatibility to support jQuery back to version 1.4.2
  • July 11, 2012
    • Added test pages to the repository
  • September 6, 2011
    • Touchy released at the San Francisco JavaScript Meetup
  • August 1, 2011
    • Formal work on Touchy began, drawing upon earlier prototypes.

Example Usage

First, load Touchy after jQuery. Touchy requires jQuery 1.4.2+.

<body>
    <!-- content -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script src="path/to/my/js/jquery.touchy.js"></script>
</body>

Then bind a Touchy event to a handler.

var handleTouchyPinch = function (e, $target, data) {
    $target.css({'webkitTransform':'scale(' + data.scale + ',' + data.scale + ')'});
};
$('#my_div').bind('touchy-pinch', handleTouchyPinch);

Touchy Events

Touchy currently enables the use of the following events:

  • touchy-longpress
  • touchy-drag
  • touchy-pinch
  • touchy-rotate
  • touchy-swipe

These events are triggered by user interactions with a specific "phase" of the user's gesture passed to the event handler. A touchy-drag event, for example, will be triggered when the user first touches the bound element, when the user drags his or her finger across the screen, and when the user stops touching the screen.

The events are all prefixed with "touchy-" to avoid name collision.

Data Passed to Event Handlers

The general pattern of the arguments passed to an event handler is as follows:

handleTouchyEvent(event, phase, $target, data);
  • event (Object) - a jQuery event object.
  • phase (String) - the phase of the user gesture: "start", "move", "end".
  • $target (Object) - a jQuery object wrapping the event target
  • data (Object) - a JSON object with additional information about the user gesture.

However, there are exceptions to this pattern. Please see below.

touchy-longpress

phase: "start" or "end" (No data object)

touchy-drag

phase: "start", "move" or "end"

data:

  • movePoint
  • lastMovePoint
  • startPoint
  • velocity

Points are JSON objects containing "x" and "y" pixel-based properties, relative to the page. Velocity is the distance / time measured in pixels and milliseconds, based on the last two ontouchmove events.

touchy-pinch

(No phase. All events are essentially within the "move" phase.)

data:

  • scale
  • previousScale
  • currentPoint
  • startPoint
  • startDistance

Scale is the percentage of the current distance between the two fingers, relative to the start distance. Points are JSON objects containing "x" and "y" pixel-based properties, relative to the page. The startDistance is measured in pixels.

touchy-rotate

phase: "start", "move" and "end"

data:

  • startPoint
  • startDate ("move" and "end" phase only)
  • movePoint
  • lastMovePoint
  • degrees
  • degreeDelta ("move" and "end" phase only)
  • velocity

Points are JSON objects containing "x" and "y" pixel-based properties, relative to the page. Velocity is the distance / time measured in pixels and milliseconds, based on the last two ontouchmove events.

touchy-swipe

(No phase. Swipe triggers only once. See configurations.)

data:

  • direction: "left", "right", "up", "down"
  • movePoint
  • lastMovePoint
  • startPoint
  • velocity

Points are JSON objects containing "x" and "y" pixel-based properties, relative to the page. Velocity is the distance / time measured in pixels and milliseconds, based on the last two ontouchmove events.

Overriding Default Configuration Settings

Touchy configurations are stored within the bound element's jQuery data object. One may override default configurations by assigning new values to properties within the data object after the element is bound to a touchy event.

Example:

$('#my_div').bind('touchy-rotate', handleTouchyRotate);
$('#my_div').data('touchyRotate').settings.requiredTouches = 2;

As shown in the example, the settings are accessed through the camelCased name of the event. All events except touchy-pinch require one finger touch by default, but may be configured to require more.

touchy-longpress

  • requiredTouches: 1
  • msThresh: 800 (the number of milliseconds the user must touch the element before the event is fired)
  • triggerStartPhase: false (whether to trigger the event during the start phase)

touchy-drag

  • requiredTouches: 1
  • msHoldThresh: 100 (a threshold before engaging drag, to avoid conflict with tapping gestures)

touchy-pinch

  • pxThresh: 0 (a pixel-based distance threshold that may be used to prevent the event from firing)

touchy-rotate

  • requiredTouches: 1

touchy-swipe

  • requiredTouches: 1
  • velocityThresh: 1 (required velocity to fire the event)
  • triggerOn: "touchmove" (or "touchend". By default, as soon as the velocity is reached, the event fires.)

Using event delegation

By default, Touchy events are not able to be bound on ancestors of the target elements in a typical "event delegation" design pattern. One may configure Touchy to do this, but unlike normal event delegation, it is computationally expensive.

To use event delegation:

$.touchyOptions.useDelegation = true;

Note that this is a global operation affecting all Touchy events.

enjoy!

touchy's People

Contributors

bfisher-hotstudio avatar fisherwebdev avatar timak304 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

touchy's Issues

tap not working

children element tab not working if its parent element have touch start and end in the latest version 1.2.1, but its working fine in 0.3 version,

handleGestureChange touches = event.touches,

In this section:

handleGestureChange: function (e) {
            var eventType = this.context,
                $target = getTarget(e, eventType);

            if ($target) {
                var $target = $(e.target),
                event = e.originalEvent,
                touches = event.touches,

Shouldn't event.touches be e.touches?

Drag and longpress confict

Is it possible to add a px threshold to drag, so that drag does not start unless the touch moved more than a certain number of pixels (similar to what is in pinch)? At present, when longpress and drag handler are both active, both get fired, because it is very difficult to perform a long touch without registering a slight move

[enhancement] Add missing bower.json.

Hey, maintainer(s) of HotStudio/touchy!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library HotStudio/touchy is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "HotStudio/touchy",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

sending 'touchy-drag' Events to PHP

Hello,

I want to log all touch-events of an user ( not only events of an specific target div).
Especially the 'touchy-drag' - Events should be logged into a file, with something like that:

function sendEventToPhp(e){
    $.post( "dump_events.php", 
    { 
        type        : "END",
        fingerID    : "0",
        x           : "345",
        y           : "678"
    } );
}

var handleTouchyDrag = function (e) {
    sendEventToPhp(e);
};
$('body').bind('touchy-drag', handleTouchyDrag);

/*
document.addEventListener('touchy-drag', function(e) {
    sendEventToPhp(e);
});
*/
  1. Due to the preventDefault, scrolling and zooming isn't working after binding to body and the document.addEventListener doesn't work.
    How can I modify that.
  2. what would be the right attributes from a touchy-drag event "e" to send. something like that ? :
    e.type
    e.id
    e.x
    e.y

Touchy 1.1: request for feedback

Here are some ideas for improving Touchy. Please let me know how this list should be prioritized or expanded.

Thanks!
~ Bill

  1. move all touchy data into the event object
  2. more cross-browser support
  3. integration with tools like grunt, npm, etc.
  4. making Touchy more compliant with trends in jQuery plugin best practices (this is a direction, not a destination)
  5. support for double tap, or the other TODO features laid out in the comments at the beginning of the code.
  6. support for binding mouse events and touch events with a single line of code ("press" and "release" instead of touchstart/mousedown, etc.)
  7. support for both mouse events and touch events on the same device (thinking in terms of laptops that have touchscreens -- the issue is to be able to handle both in the same environment.)
  8. removing jQuery as a dependency, because jQuery is a bit bloated for mobile
  9. a second sister project with a lot of common event handler code
  10. some better way of facilitating delegation -- currently, Touchy is not event-delegation-friendly.
  11. returning the angle that a drag is performed in (this is a user-requested feature)
  12. create array of formerly touched x/y point data (user-requested feature)
  13. configuration setting on a per-element basis, rather that global (user-requested feature)
  14. specify the minimal distance before a drag is considered a drag on a per associated element basis -- see #13 (user-requested feature)
  15. element time for double-tap, see #13 (user-requested feature)
  16. multi-tap, like three taps (user-requested feature)
  17. some kind of tooling/logging add-on, providing insight into the data produced by the touch interactions (user-requested feature)

Pinch and Drag within the same element

Is it possible to apply 2 different events to the same element of the page?
I'd like to pinch-zoom an image and drag it at the same time, for reading purposes inside a jQuerymobile application.

Thanks

touch-swipe - Triggered only once

I cannot understand why touch-swipe is triggered only once ? I'm building a wepapp that acts like a book and would love to be able to re-swipe pages. I tried re-binding the event in the handler, to no avail.

Any thoughts ? I really don't master the JS events so I might be just not understanding how to reuse them properly...

Thanks! Simon

Click event

Can I be made to work on click ?
I have searched on the internet and this is by far the best rotate and i tried by my self to make it work for on click but i failed.
Can you please help me ?
Thank you

touchy-pinch on iPad not working for me

I love Touchy! Am having one simple problem with version 1.1: touchy-pinch never seems to fire working on an iPad with Safari (iOS 6.1).

I traced through the Touchy code, and found that the event trigger is disabled if hasGestureChange() is true, which is the case with Safari. If I comment out the "if (!hasGestureChange())" line in the pinch code, it seems to work fine, but I'm wondering what I'm missing.

I had the same problem with the Touchy sample test.html. All else seems to work fine, but pinching doesn't fire. I know I'm doing the gesture correctly, too! :)

Any help would be appreciated.

wrong event target with useDelegation=false

When having useDelegation=false getTarget() only returns a target if the event handler was registered on exactly the same element as event.target. That means that you can't register an event handler on a div and still allow clicking on elements within that div (e.g., in our case we have a div and a canvas within that div). Instead of looking at event.target it would be better to use the element that bind() was called on.

I'm in the middle of those changes right now, so this is not yet finished, but I'm thinking of something like this:

--- jquery.touchy-orig.js       Tue Aug 21 15:45:55 2012
+++ jquery.touchy.js    Tue Aug 21 15:44:24 2012
@@ -94,9 +94,8 @@
     var proxyHandlers = {

         handleTouchStart: function (e) {
-
             var eventType = this.context,
-                $target = getTarget(e, eventType);
+                $target = getTarget(e, eventType, this.target);

             if ($target) {
                 var event = e.originalEvent,
@@ -192,7 +191,7 @@

         handleTouchMove: function (e) {
             var eventType = this.context,
-                $target = getTarget(e, eventType);
+                $target = getTarget(e, eventType, this.target);

             if ($target) {
                 var event = e.originalEvent,
@@ -336,7 +335,7 @@

         handleGestureChange: function (e) {
             var eventType = this.context,
-                $target = getTarget(e, eventType);
+                $target = getTarget(e, eventType, this.target);

             if ($target) {
                 var $target = $(e.target),
@@ -393,7 +392,7 @@

         handleTouchEnd: function (e) {
             var eventType = this.context,
-                $target = getTarget(e, eventType);
+                $target = getTarget(e, eventType, this.target);

             if ($target) {
                 var event = e.originalEvent,
@@ -507,7 +506,7 @@
          *
         handleTouchCancel: function (e) {
             var eventType = this.context,
-                $target = getTarget(e, eventType);
+                $target = getTarget(e, eventType, this.target);

             if ($target) {
                 var target = e.target,
@@ -652,11 +651,11 @@
         return points;
     },

-    getTarget = function(e, eventType){
+    getTarget = function(e, eventType, origTarget){
         var $delegate,
             $target = false,
             i = 0,
-            len = boundElems[eventType].length
+            len = boundElems[eventType].length;
         if ($.touchyOptions.useDelegation) {
             for (; i < len; i += 1) {
                 $delegate = $(boundElems[eventType][i]).has(e.target);
@@ -666,8 +665,8 @@
                 }
             }
         }
-        else if (boundElems[eventType] && boundElems[eventType].index(e.target) != -1) {
-            $target = $(e.target)
+        else {
+            $target = origTarget;
         }
         return $target;
     },
@@ -775,9 +774,11 @@
                     $(this).data('touchy' + capitalizedKey, $.extend({}, $.touchyOptions[key].data));
                     $(this).data('touchy' + capitalizedKey).settings = $.extend({}, $.touchyOptions[key]);
                     delete $(this).data('touchy' + capitalizedKey).settings.data;
-                    if ( boundElems[key].length === 1 ) {
+                    var handler = $.touchyOptions.useDelegation ? $(document) : $(this);
+                    var context = $.extend({target: handler}, contexts[key]);
+                    if ( boundElems[key].length === 1 || !$.touchyOptions.useDelegation) {
                         $.each($.touchyOptions[key].proxyEvents, function(i, proxyEvent){
-                            $(document).bind(proxyEvent.toLowerCase() + '.touchy.' + key, $.proxy(proxyHandlers['handle' + proxyEvent], contexts[key]
));
+                            handler.bind(proxyEvent.toLowerCase() + '.touchy.' + key, $.proxy(proxyHandlers['handle' + proxyEvent], context));
                         });
                     }

@@ -785,9 +786,10 @@
                 teardown: function (namespaces) {
                     boundElems[key] = boundElems[key].not( this );
                     $(this).removeData('touchy' + capitalizedKey);
-                    if ( boundElems[key].length === 0 ) {
+                    var handler = $.touchyOptions.useDelegation ? $(document) : $(this);
+                    if ( boundElems[key].length === 0 || !$.touchyOptions.useDelegation) {
                         $.each($.touchyOptions[key].proxyEvents, function(i, proxyEvent){
-                            $(document).unbind(proxyEvent.toLowerCase() + '.touchy.' + key);
+                            handler.unbind(proxyEvent.toLowerCase() + '.touchy.' + key);
                         });
                     }
                 },

Event Bubbling

Having trouble fixing the useCapture and stopping the propagation on inputs that I have inside the wheel. I have placed them in a circle using JavaScript so that it looks like a rotary telephone. I can spin the wheel and it won't accidentally click an input while spinning and touching, however, if you try and spin from an input on the wheel it will not spin.

Also... can you spin an SVG with this?

preventDefault should be optional

I had a case in which I did not want preventDefault() to be called on touchstart, etc. (I wanted to be able to swipe and use normal scrolling).
The only way to do this at the moment is to comment out the lines in the touchy lib.

Would it be possible to configure the use of preventDefault() using a setting?

Thanks

swipe events getting skipped

tested on ios 5.1

after a swipe event triggers and calls it's handler, the next swipe doesn't get called. The 3rd swipe does, and the pattern repeats.

Bug with velictyThresh (easy-swipe) in test-pages

Hi!

There is some common mistake in JavaScript of test-pages. Just compare:

$swipeArea.data("touchySwipe").settings.velocityThresh = 0.3;
RIGHT

$swipeArea.data("touchySwipe").velocityThresh = 1;
WRONG (right is the following: $swipeArea.data("touchySwipe").settings.velocityThresh = 1;)

That's why toggling easy swipe almost have no effect in demos.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.