search
HomeWeb Front-endJS TutorialHow to add Webkit touch to jQuery_jquery

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
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
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools