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){
})
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.
Just adding return false; at the end of the on("click touchstart") event function can solve this problem.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With