Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery touchstart in browser

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){
})
like image 894
coure2011 Avatar asked Feb 22 '12 06:02

coure2011


People also ask

What is touchstart in JavaScript?

The touchstart event occurs when the user touches an element. Note: The touchstart event will only work on devices with a touch screen. Tip: Other events related to the touchstart event are: touchend - occurs when the user removes the finger from an element.

How do you bind Touchstart and click events but not respond to both?

Just adding return false; at the end of the on("click touchstart") event function can solve this problem.

What is Touchstart?

The touchstart event is used to execute a script whenever the user touches an HTML element. On touching a particular element, if the touchstart event is associated with it, it can be used to trigger a javascript function. Note: The touchstart event works only on touch screen devices.

Which event is fired on a text field within a form when a user taps to it clicks it or touches it?

The touchstart event occurs when the user touches an element. But a click event is fired when the user clicks an element. Usually, both the touchstart and click events are fired in the very same click in the touch and click enabled devices.


2 Answers

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.

like image 108
alex Avatar answered Sep 18 '22 19:09

alex


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);
like image 31
Eric Steinborn Avatar answered Sep 19 '22 19:09

Eric Steinborn