Joe
Joe

Reputation: 1772

jquery - touchend preventDefault if original target was a link/image

I'm making my site touch friendly and have put created a simple carousel style plugin which works great, however when the touchend event is fired and the original target was an image (user touches image and then swipes/left to navigate) it's still opening the link associated with image.

I've put in event.stopPropagation() and event.preventDefault() but it has no effect.

Does anyone have any idea on how to prevent this?

Edit:

I'm binding the touch event using:

obj.parent().bind('touchstart', onTouchStart);
obj.parent().bind('touchend', onTouchEnd);

Here is the touchend function

function onTouchEnd(event) {
    if(!cdata.in_touch) return;
    cdata.in_touch = false;

    var pos = getPointerPosition(event);
    var final_distance = Math.sqrt(pos.x - cdata.touch_start);
    cdata.timer_end = new Date();
    cdata.timer_length = cdata.timer_end - cdata.timer_start;

    if(cdata.timer_length > 100) {
        if (final_distance > 100) {
            event.stopPropagation();
            event.preventDefault();
            // no effect, link associated with image still fires
            return;
        }
    }
}

Upvotes: 1

Views: 3609

Answers (1)

Gur Dotan
Gur Dotan

Reputation: 922

The general technique for solving this problem is to listen to touchstart. Once touchstart is fired, save the touch X-Y coordinates and attach listeners for touchend and touchmove. The touchend listener should invoke the designated callback you want to call (i.e. show the tapped image in full screen). The touchmove should monitor the distance that was moved from the original tap X-Y coordinates and if it exceeds a certain threshold, it cancels the touchend (and also the now redundant touchmove event).

There's an excellent article with reference code that does this by Google https://developers.google.com/mobile/articles/fast_buttons

And also, a new Github project by FTlabs called FastClick which is even more comprehensive; https://github.com/ftlabs/fastclick

Upvotes: 3

Related Questions