document .click function for touch device

Update! In modern browsers, the click event will be fired for a tap, so you don't need to add extra touchstart or touchend events as click should suffice.

This previous answer worked for a time with browsers that thought a tap was special. It originally included a "touch" event that actually was never standardised.

Unless you have a problem with:

$(document).on('click', function () { ... });

There is no need to change anything!

Previous information, updated to remove touch...

To trigger the function with click or touch, you could change this:

$(document).click( function () {

To this:

$(document).on('click touchstart', function () {

The touchstart event fires as soon as an element is touched, so it may be more appropriate to use touchend depending on your circumstances.


touchstart or touchend are not good, because if you scroll the page, the device do stuff. So, if I want close a window with tap or click outside the element, and scroll the window, I've done:

$(document).on('touchstart', function() {
    documentClick = true;
});
$(document).on('touchmove', function() {
    documentClick = false;
});
$(document).on('click touchend', function(event) {
    if (event.type == "click") documentClick = true;
    if (documentClick){
        doStuff();
    }
 });

can you use jqTouch or jquery mobile ? there it's much easier to handle touch events. If not then you need to simulate click on touch device, follow this articles:

iphone-touch-events-in-javascript

A touch demo

More in this thread

Tags:

Css

Jquery