jquery touchstart in browser

半腔热情 提交于 2019-11-28 09:04:20

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);
Maciej Paprocki

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!