I have the following jQuery plugin that binds touch events and moves an element.
In the functions moveMe
and snap
, there is duplicate code doing the same thing because I couldn't figure out how to refactor the scope of the functions to only do this once.
$.fn.draggable = function(limit) {
var offset = null;
var start = function(e) {
var orig = e.originalEvent;
var pos = $(this).position();
offset = {
x: orig.changedTouches[0].pageX - pos.left,
//y: orig.changedTouches[0].pageX - pos.top
};
$(this).stop(true,false);
};
var moveMe = function(e) {
e.preventDefault();
$('body').css('overflow-x','hidden');
var orig = e.originalEvent;
var touchX = orig.changedTouches[0].pageX;
var difference = touchX - offset.x;
var move;
if (difference >= limit) {
move = limit;
} else if (difference <= 0) {
move = 0;
} else {
move = difference;
}
$(this).css({
left: move,
//left: orig.changedTouches[0].pageX - offset.x
});
};
var snap = function(e) {
var orig = e.originalEvent;
var touchX = orig.changedTouches[0].pageX;
var difference = touchX - offset.x;
var threshold = limit*0.75;
if (difference >= limit) {
move = limit;
} else if (difference <= 0) {
move = 0;
} else {
move = difference;
}
if (threshold > (limit-move)) {
$(this).animate({
left : limit
});
} else {
$(this).animate({
left : 0
});
}
};
this.bind("touchstart", start);
this.bind("touchmove", moveMe);
this.bind("touchend", snap);
};
$("#container").draggable(200);