Home Web Front-end JS Tutorial How to add Webkit touch to jQuery_jquery

How to add Webkit touch to jQuery_jquery

May 16, 2016 pm 05:01 PM
webkit

This code was added out of boredom when I was working a part-time job for 13 years to add support for touch events to jQuery. Because it was a bit boring, I helped the customer add a responsive web page using JS touch that is compatible with mobile devices, mainly Webkit mobile devices.

Here I will share my implementation.
Paste the code first:

Copy code The code is as follows:

//Published by Indream Luo
//Contact: indreamluo@qq.com
//Version: Chinese 1.0.0

!function ($) {
    window.indream = window.indream || {};
    $.indream = indream;

    //Define events
    indream.touch = {
        evenList: {
            touchStart: {
                htmlEvent: 'touchstart'
            },
            touchMove: {
                htmlEvent: 'touchmove'
            },
            touchEnd: {
                htmlEvent: 'touchend'
            },
            tapOrClick: {
                eventFunction: function (action) {
                    $(this).each(function () {
                        (function (hasTouched) {
                            $(this).touchEnd(function (e) {
                                hasTouched = true;
                                action.call(this, e);
                            });
                            $(this).click(function (e) {
                                if (!hasTouched) {
                                    action.call(this, e);
                                }
                            });
                        }).call(this, false);
                    });

                    return this;
                }
            },
            moveOrScroll: {
                eventFunction: function (action) {
                    $(this).each(function () {
                        (function (hasTouched) {
                            $(this).touchMove(function (e) {
                                hasTouched = true;
                                action.call(this, e);
                            });
                            $(this).scroll(function (e) {
                                if (!hasTouched) {
                                    action.call(this, e);
                                }
                            });
                        }).call(this, false);
                    });

                    return this;
                }
            }
        }
    }

    //Add events into jquery
    for (var eventName in indream.touch.evenList) {
        var event = indream.touch.evenList[eventName];
        $.fn[eventName] = event.eventFunction || (function (eventName, htmlEvent) {
            return function (action) {
                $(this).each(function () {
                    $(this).bind(htmlEvent, action);
                    //Add event listener method for IE or others
                    if (this.attachEvent) {
                        this.attachEvent('on' htmlEvent, function (e) {
                            $(this).on(eventName);
                        });
                    } else {
                        this.addEventListener(htmlEvent, function (e) {
                            $(this).on(eventName);
                        });
                    }
                });

                return this;
            }
        })(eventName, event.htmlEvent);
    }
}(window.jQuery);

A lot of relevant information about Touch events can be found online, so I won’t explain it in detail. I can explain it simply.

Touch events replace mouse events
On Webkit mobile devices, touch controls will first trigger touch events, and then touch mouse events after 0.5 seconds.

Personally, I think this is understandable in terms of design. First meet the needs of touch control, and then "downward" compatibility with mouse events to meet the use of original desktop-oriented web pages.

The approximate execution order of all events is: touchstart->touchmove->touchend->0.5s->mouse events mouseover/scroll/click, etc.

According to the design of webkit mobile browser, it is generally no problem to develop according to desktop web pages and then use them on mobile devices. However, hover effects that are widely used on the desktop are often tragic because the mouse event and click event are triggered over and over again by touch; the 0.5 second delay also causes great harm to the user experience.

So I added the tapOrClick event to replace the click event and extinguish it for 0.5 seconds.

Scroll Lock
When the user uses a touch device to scroll and the touch has stopped, the browser will lock the entire page, suspend all UI resource occupation, and leave most resources to the kernel for scrolling. The same situation will occur when zooming in and out of page content, even more so.

Because I want to add a rolling gradient effect, I added the moveOrScroll event to perform the effect that should be performed during scrolling when sliding.

Of course, this is still not perfect, because once the finger leaves the screen (the touch event stops), the js will also be frozen during the period when the page scrolls freely. This is just the solution within no solution.

Scroll lock will also cause another problem: there are three types of scrolling, namely up and down, left and right, and free.

If you use the touch device, you will find that if it is judged to be scrolling up and down from the touch, then no matter how you slide left or right when touching, there will be no left or right sliding effect unless you let go and start over. The same thing happens at the beginning for left and right scrolling. Free scrolling requires diagonal scrolling from the beginning.

If you need to add a specific event at this time, you need to pay attention to the judgment of the event. In the event callback parameter of jQuery, assuming the parameter name is e, then generally use:

e.originalEvent.touches[0].pageX can determine the touch situation. During development, you need to record the touch events yourself before making a judgment.

Native and optimal
Please try not to use a large number of JS method triggers to achieve some style effects that you don’t have.

For example, if the element is static, it should be implemented using position:fix;, but many developers will use js to continuously refresh the position of its control.

When this implementation is placed on a touch device, there are generally only two situations:

1. You are stuck
2. The page is frozen. After the freezing technology, it is suddenly discovered that all events have been executed (the reason is as above, the browser will concentrate the resources of the UI thread to give priority to the kernel)
The screen of a general mobile device The effective refresh rate is only 30Hz, and the reduced instruction set CPU itself will be slower, plus most mobile devices are...Android...

Therefore, performance must rely as much as possible on natively provided methods. Some hack and cover methods are intolerable to the other party.

How to use it
At that time, the part-time delivery seemed to only take a week or two, so I didn’t write the code very well, but it still worked. The general usage is the same as that of ordinary jQuery events. The naming and implementation are indeed debatable:

Copy code The code is as follows:

$('.sign .usernametip').tapOrClick( function () {
$(this).css('visibility', 'hidden');
$('.sign .username').focus();
});

Like many things in the project, many things seem simple, but in fact various problems will arise.

Touch events are not simply compatible. In addition to realizing the function, you also need to consider the most essential issue - a specific interaction mode.

For example, a lot of space needs to be hidden in touch to leave more space for the limited user screen; many elements that are switched by clicking should be changed to sliding switching for the best experience of touch, and even different sliding conditions must be considered ; Different stay events of each touch event may represent different operations and need to be distinguished...

Although I know that jQuery Mobile and others already have various relatively complete methods, I just can’t help but implement it myself.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

See all articles