Javascript catch different touch on same object

Here is a basic trick to have two different callbacks, regarding the time pressed :

Object.prototype.doubleTouch = function(shortCallback, longCallback){
	this.doubleTouchTime = null;
	this.shortcallback = shortCallback;
	this.longcallback = longCallback;
	var that = this;

	this.onmousedown = function(){
		that.doubleTouchTime = window.setTimeout(function(){
			var notNull = (that.doubleTouchTime != null);
			clearTimeout(that.doubleTouchTime);
			that.doubleTouchTime = null;
			if(notNull){
				that.longcallback();
			}
		}, 400);
	}
	this.ontouchstart = this.onmousedown;

	this.onmouseup = function(){
		var notNull = (that.doubleTouchTime != null);
		clearTimeout(that.doubleTouchTime);
		that.doubleTouchTime = null;
		if(notNull){
			that.shortcallback();
		}
	}
	this.ontouchend =this.onmouseup;
}

Here is a simple way to use it (suppose a <a id= »test »>click me</a> on HTML side) :

var myLabel = document.getElementById("test").doubleTouch(function(){
  alert("I'm a short touch");
}, function(){
  alert("I'm a long touch");
}

If, for any reason, you can’t touch or you don’t want to touch the Object prototype, you can do also the following :

function doubleTouch(el, shortcallback, longcallback){
	this.time = null;
	this.shortcallback = shortcallback;
	this.longcallback = longcallback;
	var that = this;

	el.onmousedown = function(){
		that.time = window.setTimeout(function(){
			var notNull = (that.time != null);
			clearTimeout(that.time);
			that.time = null;
			if(notNull){
				that.longcallback();
			}
		}, 400);
	}
	el.ontouchstart = el.onmousedown;

	el.onmouseup = function(){
		var notNull = (that.time != null);
		clearTimeout(that.time);
		that.time = null;
		if(notNull){
			that.shortcallback();
		}
	}
	el.ontouchend = el.onmouseup;
}

Here is a simple way to use it (suppose a click me on HTML side) :

var myLabel = document.getElementById("test");

new doubleTouch(myLabel, function(){
  alert("I'm a short touch");
}, function(){
  alert("I'm a long touch");
}

See the notNull created : in case of alert, the lock system will force the double touch system to pull the two callback, because the alert block everything. The only way to have the good touch system is to catch the timer state BEFORE anything block it… This is why there is a notNull var created here.

Publicités

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s

%d blogueurs aiment cette page :