Created
January 6, 2012 18:25
-
-
Save pamelafox/1571791 to your computer and use it in GitHub Desktop.
Touch/click events wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ISTOUCHING = false; | |
function useTouchEvents() { | |
return isTouchDevice(); | |
} | |
function triggerClick(dom) { | |
if (useTouchEvents()) { | |
dom.trigger('tap'); | |
} else { | |
dom.trigger('click'); | |
} | |
} | |
function addClickHandler(dom, callback, logThis) { | |
if (useTouchEvents()) { | |
dom.each(function() { | |
$(this).unbind('tap', callback); | |
$(this).bind('tap', callback); | |
$(this).bind('touchstart', function(e) { | |
e.preventDefault(); | |
var item = e.currentTarget; | |
if (ISTOUCHING) return; | |
item.moved = false; | |
ISTOUCHING = true; | |
item.startX = e.touches[0].pageX; | |
item.startY = e.touches[0].pageY; | |
$(item).addClass('active'); | |
}); | |
$(this).bind('touchmove', function(e) { | |
var item = e.currentTarget; | |
if (Math.abs(e.touches[0].pageX - item.startX) > 10 || | |
Math.abs(e.touches[0].pageY - item.startY) > 10) { | |
item.moved = true; | |
$(item).removeClass('active'); | |
} | |
}); | |
$(this).bind('touchend', function(e) { | |
var item = e.currentTarget; | |
ISTOUCHING = false; | |
if(!item.moved) { | |
$(item).trigger('tap'); | |
} | |
setTimeout(function() { | |
$(item).removeClass('active'); | |
}, 1000); | |
delete item.moved; | |
}); | |
}); | |
} else { | |
dom.unbind('click', callback).bind('click', callback); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment