gregavola
gregavola

Reputation: 2539

Converting onClick methods over to tap methods in Zepto

Is there a simple to re-write links on a mobile web-app from onclick to tap using Zepto? Currently I want to fire the $.tap command for every instance of onclick.

For example

<a href="#" tap="doSomething(); return false;">Link</a>

Is this possible, or is there a way to prevent the onclick from firing, but take the onclick method and call it inside the $.tap method?

Any suggestions for making fast buttons using Zepto?

Upvotes: 2

Views: 4311

Answers (2)

Huangism
Huangism

Reputation: 16448

ok so the way i understand you is you want different behaviors on mobile and desktop but with the same code. If so then you need to identify which platform you are on then define your code

if(MOBILE) {
    $('element').click(function(){
        return false;
    });

    $('element').on('touchstart', function(){
        // functionality of the onclick written here
    });
}
else {
// desktop event listeners
}

Upvotes: 0

ChillyPenguin
ChillyPenguin

Reputation: 1180

A more elegant way would be to store your click trigger in a variable and then remap that variable from "click" to "touchstart" when you're dealing with a touchscreen device.

Here, I use a global object variable, myUtils, to store my click event, which defaults to "click" as its value:

var myUtils = myUtils || {};
myUtils.events = myUtils.events || {
  click : "click"
};

If there's a touchscreen detected, then I change my myUtils.events.click property to have a value of "touchstart":

if (typeof document.body.ontouchstart !== "undefined") {
  myUtils.events.click = "touchstart";
}

Now, when I'm binding my click events to my elements, I use my myUtils.events.click property for name of the event:

$(function() {
   $("#link").bind(myUtils.events.click, function(e) {
     alert("I'm a " + e.type);
     e.preventDefault();
   });
});​

This way I only have to do the "is it a touchscreen?" test once in my application and I will bind to either "touchstart" or "click" as needed thereafter. I don't have to worry about cancelling the unwanted click event on a mobile device, since that event is never bound in the first place.

The e.preventDefault() call will prevent the link from being followed (assuming #link is an href link).

JSFiddle version: http://jsfiddle.net/BrownieBoy/Vsakw/

Be warned that this code assumes that a touchscreen device is only a touchscreen device; i.e. a phone or a tablet. If you're on a touchscreen PC then you won't be able to use it with a mouse!

Upvotes: 2

Related Questions