As touchstart/touchend is yet not supported in most of the desktop browsers. How can I create touchstart event that will be the same as mousedown event (that is supported in
You can bind both at once...
$('obj').bind('touchstart mousedown', function(e){
});
If you want to mousedown
event to fire touchstart
events automatically (so you only need to bind touchstart
) use...
$(document).bind('mousedown', function(event) {
$(event.target).trigger('touchstart');
});
Note that this means mousedown
events must propagate to document
before the custom touchstart
event can be triggered. This could have unexpected side effects.
Try something like this:
var clickEventType = ((document.ontouchstart!==null)?'click':'touchstart');
$('obj').bind(clickEventType, function(e){});
Better yet, use .on() for binding:
$('body').on(clickEventType, 'obj', function(e){});
This checks document to see if touchstart exists, if it does, then your event is 'touchstart' if it doesn't (most desktop browsers) then its 'click'.
You can also trigger using the same event type:
$('obj').trigger(clickEventType);
It's not the nicest solution, but the best I found till now. Downfall? It only works after first touch happened so you cannot use synchronously :(
var isTouch = false;
$('body').on('touchstart', function () {
isTouch = true;
});
You can also check if browser support touch first with modernizr for example.
Remember to don't use it in global scope (unless you have to). You can also change it to be modernizr "alike" by adding is-touch-device class to Html tag by adding after isTouch = true
code: $('html').addClass('is-touch-device')
. In this case you can reference it from everywhere (from css also).