Is there a more elegant way to detect support for touch events and assign a click or touchhend event?

var ClickOrTouchEvent = ("ontouchend" in document.documentElement ? "touchend" : "click"); $("#MyButton").on(ClickOrTouchEvent, function () { // Do something }); 

This works, but perhaps a more elegant way of detecting support for touch events and assigning a click or touchhend event.

+4
source share
1 answer

There are many plugins created by people to add more advanced touch support to their jquery-based web applications, such as drag and drop. You can use one of them instead of trying to make your own.

This suggests that everyone seems to have their strange problems in my experience, so you probably have to make friends. It looks like your decision is in the same family as most of them. Here are a couple of popular plugins and solutions that they use to solve a touch or tap:

TouchPunch adds a touch to everything like this:

 // Detect touch support and save it in support $.support.touch = 'ontouchend' in document; // Ignore browsers without touch support if (!$.support.touch) { return; } //rest of plugin code follows 

jquery-ui-for-ipad-and-iphone has a method that you must call to add touch events to the desired element ... but only if the browser supports it.

 // Same deal. Detect touch support and save it in support $.extend($.support, { touch: "ontouchend" in document }); // // Hook up touch events // $.fn.addTouch = function() { if ($.support.touch) { this.each(function(i,el){ el.addEventListener("touchstart", iPadTouchHandler, false); el.addEventListener("touchmove", iPadTouchHandler, false); el.addEventListener("touchend", iPadTouchHandler, false); el.addEventListener("touchcancel", iPadTouchHandler, false); }); } }; .... 

Then call addTouch on the elements using jQuery's user interface functions:

 $('Element').dialog().addTouch(); 
+3
source

All Articles