Touch device friendly click events with JQuery
I discovered on certain Android devices (i.e. Samsung S5), the “click” event wouldn’t fire on elements that weren’t naturally clickable, like
‘s and ‘s – I tried the usual hacks like cursor:pointer and an empty onclick handler, but neither worked reliably.
I noticed that touchstart and touchend worked, but the side effect was that it interfered with scrolling, since if you tried to scroll the page, it would also fire the touch events.
Although I did notice that a scroll was always a combination of a touchmove and touchend – So, by suppressing the touchend event if it was preceded by a touchmove meant the user’s intent was to click, not scroll.
Now, to minimize code change, and there was plenty of $(whatever).bind(“click”…’s throughout the app, I wanted to create a jquery plugin that I could drop into the page.
(function($) {
$.fn.touchClick = function(action) {
this.each( function() {
$(this).bind(“touchmove”,function(){
$(this).attr(“ignore”,”touchend”);
setTimeout(function()
{
$(this).attr(“ignore”,””);
},1000);
});
$(this).bind(“touchend”,function(event){
if ($(this).attr(“ignore”) != “touchend”)
{
$.proxy(action,this)(event);
}
});
});
}
}(jQuery));
– And that’s what I came up with. The tricky part was the $.proxy(action,this)(event), which basically maintains the (this) variable so I could rewite code from $(whatever).bind(“click”,function(){ this…}) to $(whatever).touchClick(function(){this…)
Hope no other surprises!