search
HomeWeb Front-endCSS TutorialExample of native implementation of FastClick event in js

Note: I have not been learning JavaScript for a long time. I have been working on mobile web pages and WeChat applications on the web recently. Since I have recently used functions similar to fastclick, I used touchstart and touchend events to simulate them in the original program. Now I am trying to encapsulate them. The following two problematic solutions were obtained. Share it with everyone, and ask for guidance from the master

In mobile web app development, the 300ms delay of the click event will cause slow response, especially in low-end machines. Using touchstart or touchend events will conflict with the default wheel event, which is not what we expect.

So, I did it myself, had enough food and clothing, and wrote a native js code for a quick click event (considering the environment of web app development, we do not need to consider compatibility with browsers such as IE for the time being).

Implementation method 1 is as follows:

function FastClickEvent(handler){
  var fastclick = {
    handler : handler,
    bind : function(query){
      var targetList = document.querySelectorAll(query);
      for(var i=0,len=targetList.length;i<len;i++)
      {
        targetList[i].addEventListener(&#39;touchstart&#39;,handleEvent);
        targetList[i].addEventListener(&#39;touchend&#39;,handleEvent);
      }
    },
    unbind : function(query){
      var targetList = document.querySelectorAll(query);
      for(var i=0,len=targetList.length;i<len;i++)
      {
        targetList[i].removeEventListener(&#39;touchstart&#39;,handleEvent);
        targetList[i].removeEventListener(&#39;touchend&#39;,handleEvent);
      }
    } 
  }
  var touchX = 0 ,touchY = 0;
 
  function handleEvent(event){
    switch(event.type)
    {
      case &#39;touchstart&#39;:
        touchX = event.touches[0].clientX;
        touchY = event.touches[0].clientY;
        break;
      case &#39;touchend&#39;:
        var x = event.changedTouches[0].clientX;
        var y = event.changedTouches[0].clientY;
        if(Math.abs(touchX-x)<5||Math.abs(touchY-y)<5)
          fastclick.handler(event);
        break;
    }
  };
 
  return fastclick;
};

Principle: Based on the change in position when continuous touchstart and touchend events occur, determine whether it is a click

Call: Use a handler function to register a FastClickEvent event. Then bind the registered FastClickEvent event to the corresponding element through the bind method. As follows:

var handler = function(event){
  console.log(event.target.id+" fastclicked");
}
var fastClick = new FastClickEvent(handler);
fastClick.bind("div");

In this code, we register the fastclick handler event for all div elements. Call fastClick.unbind to unbind an element.

But there is a problem with this code, in order to allow the handleEvent event to access touchX, touchY. I used a closure method, which means that every time a new FastClickEvent event object is created, a repeated handleEvent function must be injected into the memory. As for the repeated touchX and touchY, there is no need to say more.

Newbie help: I ​​originally wanted to write the handleEvent function into the prototype, but a problem arises is that the this object of handleEvent (event) is windows, that is to say, I cannot get the touchX, touchY and handler objects, causing an access error. .

There is a relatively simple solution, which is to only register one fastClickEvent event, and then determine the response content in the handler based on the actual value of event.target (that is, the object where the event occurs).

However, this means you must be very familiar with all fastclick events.

The advantage of using this method is that since you only have one handleEvent function, basically, before the page is released, unless you don’t want to trigger the fastclick event anymore, you don’t need to unbind the fastclick event of any element (even if If you unbind it, the handler function still exists in the memory). Moreover, you can easily use bind(query) to add the fastclick event of any dynamically generated element, as long as you have written the corresponding handler in the handler function.

If you want to add multiple fastclick events, and you may need to register them in multiple places, you only need to create a new FastClickEvent object and bind it to the corresponding element.

The following is a method of using the EventTarget class. First, let’s take a look at the EventTarget

function EventTarget(){
  this.handlers = {};
}
EventTarget.prototype = {
  constructor: EventTarget,
  addHandler : function(type,handler){
    if(typeof this.handlers[type] == "undefined"){
      this.handlers[type]=[];
    }
    this.handlers[type].push(handler);
  },
  fire : function(event){
    if(!event.target){
      event.target = this;
    }
    if(this.handlers[event.type] instanceof Array){
      var handlers = this.handlers[event.type];
      for(var i=0,len=handlers.length;i<len;i++){
        handlers[i](event);
      }
    }
  },
  removeHandler : function(type,handler){
    if(this.handlers[type] instanceof Array){
      var handlers = this.handlers[type];
      for(var i=0,len=handler.length;i<len;i++){
        if(handlers[i]==handler){
          break;
        }
      }
      handlers.splice(i,1);
    }
  }
}

class, which is an interface used to add, remove and implement custom classes. Refer to "JavaScript Advanced Programming Third Edition" P616-617

So, how to turn this class into our fastclick event interface?

Define a global variable and use this variable to complete all fastclick event registration, deletion and addition

var FastClick = function(){
 
  var fastclick = new EventTarget(),
    touchX = 0 ,
    touchY = 0;
 
  function handleEvent(event){
    switch(event.type)
    {
      case &#39;touchstart&#39;:
        touchX = event.touches[0].clientX;
        touchY = event.touches[0].clientY;
        break;
      case &#39;touchend&#39;:
        var x = event.changedTouches[0].clientX;
        var y = event.changedTouches[0].clientY;
        if(Math.abs(touchX-x)<5||Math.abs(touchY-y)<5)
          fastclick.fire({type:&#39;fastclick&#39;,target:event.target});
        break;
    }
  };
  fastclick.bind = function(query)
  {
    var targetList = document.querySelectorAll(query);
    for(var i=0,len=targetList.length;i<len;i++)
    {
      targetList[i].addEventListener(&#39;touchstart&#39;,handleEvent);
      targetList[i].addEventListener(&#39;touchend&#39;,handleEvent);
    }
  }
 
  Fastclick.unbind = function(query){
    var targetList = document.querySelectorAll(query);
    for(var i=0,len=targetList.length;i<len;i++)
    {
      targetList[i].removeEventListener(&#39;touchstart&#39;,handleEvent);
      targetList[i].removeEventListener(&#39;touchend&#39;,handleEvent);
    }
  }
  return fastclick;
}();

This global variable FastClick can be used to add any fastclick event.

Let’s talk about how to call it.

Add event function:

FastClick.addHandler('fastclick',function(event){});

Delete event function: //Anonymous events cannot be deleted

FastClick.removeHandler('fastclick',handler);

Binding elements

FastClick.bind("div");

Unbinding

FastClick.unbind("div");

Using this method, we also need to predict the event.target in the handler event , because although this method can add multiple fastclick events, the events are executed one by one in sequence during execution, which means that functions you do not want to execute may be executed. The benefit of

is that multiple fastclick events can be registered and executed without binding again.
For example,

FastClick.bind("div");
FastClick.addHandler(handler1);
FastClick.addHandler(handler2);

Then, when a quick click event occurs on any div element, handler1 and handler2 will be executed sequentially.

If we call removeHandler to delete handler1 or handler2, the corresponding function will no longer be executed.

In addition, it should be noted that in the handler function, this object is the array FastClick.handlers['fastclick']. Generally, we use event.target to obtain the object where the event occurred.

Using this method basically overcomes the problems of the above method. Moreover, repeating new for this object does not make much sense unless you don’t want to predict the event.target and generate a lot of FaskClick classes, but this Obviously it's not efficient.

Newbie help: How can I implement a binding execution function for a specific element, that is: I can call FastClick.bind(query,handler); to implement the fastclick event of adding a handler to elements that meet the query conditions.


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
CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.