JS Touch Event Introduction

Source: Internet
Author: User

With the popularity of smartphones and tablets, more and more people use mobile devices to browse the Web, we usually use on the PC browser mouse events, such as: Click, MouseOver, etc., has been unable to meet the characteristics of mobile device touch screen, touch the arrival of the times, inseparable from those touch events.

A touch event contains 4 interfaces.

TouchEvent

Represents an event that occurs when a touch behavior changes on a plane.

Touch

Represents a point of contact between the user's finger and the touch plane.

Touchlist

Represents a series of touch; This interface is typically used when the user has multiple fingers touching the touch plane at the same time.

Documenttouch

Contains some handy ways to create touch objects and Touchlist objects.

(Refer to https://developer.mozilla.org/zh-CN/docs/Web/API/Touch_events )

The TouchEvent interface responds to basic touch events such as single finger clicks, which contain specific events,

Event Type :

touchstart : Touch Start (finger on touch screen)

touchmove : dragging (fingers moving on the touchscreen)

touchend : End of touch (finger removed from touch screen)

touchenter : Move the finger into a DOM element.

touchleave : Move the finger away from a DOM element.

There is also a touchcancel, which is triggered when the drag is interrupted.

Event Properties :

Altkey : This property returns a Boolean value that indicates whether the ALT key is in the pressed state when the specified event occurs, event.altkey=true|false|1|0

Type: Types of events triggered when touching, such as Touchstart

Each touch event includes a list of three touch attributes:

1. touches: A list of all finger touch points currently located on the screen.

2. targettouches: A list of all touch points on the current element object.

3. changedtouches: A list of touch points that involve the current event.

They are all an array and each element represents a touch point.

Each touch point has three pairs of important properties, Clientx/clienty, Pagex/pagey, and Screenx/screeny.

where Screenx/screeny represents the offset for the screen where the event occurred, both Clientx/clienyt and pagex/pagey represent the offset of the object where the event occurred, but the difference is that Clientx/clienty does not include the object roll

offset, while Pagex/pagey includes object scrolling and hidden offsets volume. The touch point that removes the screen is only included in the Changedtouches list, not in the touches and targettouches column tables, so changedtouches is more commonly used in the project.

Example:

<body onload="start ();"><style type="Text/css">#dom {width:500px;  height:500px; Background:black;}</style><div id="Dom"></div><script type="Text/javascript">function Ontouchstart (e) {console.log (e);} function Start () {varDom = document.getElementById ('Dom'); Dom.addeventlistener ('Touchstart', Ontouchstart,false);}</script></body>

The console output is as follows:

Trigger order of touch events and mouse events:

Touchstart > Toucheend > MouseMove > MouseDown > MouseUp > click

in many cases, touch events and mouse events are triggered at the same time (to allow code that is not optimized for touch devices to still work on touch devices), and if touch events are used, you can call Event.preventdefault () to prevent mouse events from being triggered. While the finger moves on the screen touchmove does not trigger mouse events and click events, adding Preventdefault to the Touchmove event prevents the browser from rolling the screen and does not affect the trigger of the Click event.

The above events, which are built-in, can be used directly, through these built-in events, can be combined into many non-native multi-touch gesture touch gestures.

Hammer.js is a lightweight JavaScript library that makes it easy for your site to touch events and relies on jquery to control multitouch features on touch devices.

Official website: http://hammerjs.github.io/

Multi-touch implementation, want to know more can refer to: http://www.cnblogs.com/iamlilinfeng/p/4239957.htm

Zepto is a lightweight and compatible juqery library, suitable for mobile development, the use of specific methods, can be see the official website, http://zeptojs.com/

Zepto Touch is a touch event module for single-point gesture triggering.

Touch.js: https://github.com/madrobby/zepto/blob/master/src/touch.js

First look at the Zepto Touch module implementation:

$ (document). On ('Touchstart ...', Function (e) {... now=date.now () Delta= Now-(Touch.last | |Now )if(Delta >0&& Delta <= -) Touch.isdoubletap =trueTouch.last=Now }) . On ('touchmove ...', Function (e) {}). On ('touchend ...', Function (e) {...if(DeltaX < -&& DeltaY < -) {                   var Event= $. Event ('Tap') Touch.el.trigger (Event)            }     })      

The touch module binds events Touchstart, Touchmove, touchend to document, and then implements a custom Tap,swipe event by calculating the difference in the event-triggered time difference.

There is also a click event on the phone, from touch to response to the Click event, with a delay of 300 milliseconds due to:

" Apple is ready to release the iphone, in order to solve the mobile phone on the Web page is too small, increased the ability to double-click on the screen, (double tap to zoom), when the user touch the screen, the browser does not know whether the user is to double tap or click, So the browser after the first tap event will wait for 300ms to determine whether it is a double tap or click, if you click within 300ms, you will think it is a double tap, and vice versa is click. "

To remove the Click event 300ms method:

(1) In Meta, add user-scalable=no can prevent double-click to enlarge, (disadvantage: some browsers support)

(2) using Fastclick.js it uses the encapsulation of native events such as multi-touchstart touchmove to realize various gestures on the phone, such as tap, swipe, etc.

Https://github.com/ftlabs/fastclick

The call is simple:

$ (function () {    Fastclick.attach (document.body);});

Cons: File size is a bit large, in order to solve a small delay problem, a little outweigh the gains.

Custom events

 //Creating an Event object  varobj =NewEvent ('Sina'); varElem = document.getElementById ('Dom'); //Monitoring Sina EventsElem.addeventlistener ('Sina', Function (e) {console.log (e); },false); //Distributing Sina Eventselem.dispatchevent (obj);

Another way to create an event object is through Customevent, which, compared to the event's benefit, can give the function that handles events, custom detail values, which may be used frequently in real-world development.

  //Creating an Event object  varobj =NewWindow. Customevent ('Sina', {detail: {'name':'Lily'}  }); varElem = document.getElementById ('Dom'); //Monitoring Sina EventsElem.addeventlistener ('Sina', Function (e) {//you can receive the detail value that was passed in when the event was created. Console.log (E. detail); //{' name ': ' Lily '}  },false); //Distributing Sina Eventselem.dispatchevent (obj);

Create custom events, a better-compatible function:

Zepto tap "point through" problem

The tap event of Zepto is implemented by binding the Touchstart and Touchend events through document, if the DOM element that binds the tap method is hidden after the tap method is triggered and "hidden, There is exactly one DOM element at the bottom of it that binds the click event, and the Clic event has a 300ms delay, triggering the Click event. There will be a "point through" phenomenon.

Solution:

1 fastclick.js

the actual principle is to bind the Touchstart, Touchend event on the target element, and then in the Touchend this library triggers the Click event on the DOM directly at Touchend, replacing the original trigger time, The touch event is bound to the specific DOM, not the document, so E.preventdefault is valid, can block bubbling, and can block browser default events.

Http://www.cnblogs.com/yexiaochai/p/3442220.html

2, the use of Fastclick event principle, directly write a paragraph, the use of E.preventdefault (); Blocking the default behavior, binding events to DOM elements, has the disadvantage that the event proxy cannot be used.

Elem.addeventlistener (Touchend, function (e) {E.preventdefault ()
},false);

3. During the event capture phase, if the time difference, the difference in location, is less than the specified value, the triggering of the bubbling and default click events is blocked.

4. When users click on the "Pop Up" a top-level div, shielding off all event delivery, and then automatically hide the timing, this method is more ingenious.

Reference:

Tap Module

Https://github.com/alexgibson/tap.js

Ghost Click

http://ariatemplates.com/blog/2014/05/ghost-clicks-in-mobile-browsers/

JavaScript and Events

http://f2e.im/t/850

Welcome message to add, thank you.

JS Touch Event Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.