22

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 all browsers).

I want something like this

$('obj').bind('touchstart', function(e){
});

will be translated into

$('obj').bind('mousedown', function(e){
})
coure2011
  • 40,286
  • 83
  • 216
  • 349

3 Answers3

30

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.

alex
  • 479,566
  • 201
  • 878
  • 984
  • 3
    These solutions might prove to be a bit problematic if at some point both events will be supported by the same device. – epeleg Jun 21 '12 at 07:54
  • @epeleg Definitely. In that case, you'd have some code like `"ontouchstart" in document` or similar, and then choose your event name accordingly. – alex Feb 14 '14 at 23:18
  • Perhaps something like `if (Modernizr.touchstart){}` would be appropriate? – Phil Tune Jan 30 '15 at 14:18
9

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);
Eric Steinborn
  • 800
  • 1
  • 7
  • 14
1

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).

mjepson
  • 871
  • 1
  • 9
  • 21
Maciej Paprocki
  • 1,230
  • 20
  • 29