简体   繁体   中英

A Better Way to Detect Touch vs Click Events

So, I've gone through many iterations of my code, but I think I've finally come up with the ultimate way to detect click vs tap events using a universal jQuery plugin. The plugin requires a hidden input field to store the "touchMove" flag. Does anyone know of a way (looking at my code) to store the flag in a global variable? I tried declaring a global touchMove variable, but unfortunately, javascript functions copy global variables to a local copy within the scope.

Anyway, here's what I got:

 $(document).ready(function() { $("#touch-me").touch(function() { console.log("I have been activated!"); }); }); $.fn.touch = function(callback) { var touch = false; $(this).on("click", function(e) { if (!touch) { console.log("I click!"); let callbackReal = callback.bind(this); callbackReal(this, e); } else { touch = true; } touch = false; }); $(this).on("touchend", function(e) { $(this).blur(); if (typeof e.touches != typeof undefined) { e.preventDefault(); touch = true; if ($("#touchMove").val() == 'moved') { console.log("You moved your finger, so I quit!"); $("#touchMove").val(''); return false; } else { console.log("I touch!"); let callbackReal = callback.bind(this); callbackReal(this, e); } } }); $(this).on("touchmove", function(e) { $("#touchMove").val('moved'); }); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="touch-me">Touch or Click on ME</button> <input type="hidden" id="touchMove" value="" /> 

I also have my code on GitHub: https://github.com/cloudmedia/jQuery.touch.js

And here is a fiddle: https://jsfiddle.net/cloudulus/7n9deqxb/

Any suggestions to improve my code would be greatly appreciated.

Here is the final code as edited by @Shikkediel:

 $.fn.touch = function(callback) { $.touch = { action: "", move: false, event: false } return this.on("click", function(e) { if (!$.touch.event) { $.touch.action = "click"; let callbackReal = callback.bind(this); callbackReal(this, e); } $.touch.event = false; }) .on("touchend", function(e) { $(this).blur(); $.touch.event = true; if ($.touch.move) { $.touch.move = false; return; } else { $.touch.action = "touch"; let callbackReal = callback.bind(this); callbackReal(this, e); } }) .on("touchmove", function() { $.touch.move = true; }); } $("#clickme").touch(function() { console.log("Action: " + $.touch.action); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="clickme">Click or Touch Me!</button> 

Great job, Shikkediel. Thank you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM