0
\$\begingroup\$

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);
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 10, 2012 at 17:18
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Could you write something like this?

var limited = function( value, limit ){
 if (value >= limit) { 
 return limit; 
 } else if (value <= 0) { 
 return 0; 
 } else { 
 return value; 
 } 
}

then, when you need to work out move, just write move = limited( difference, limit );

answered Mar 11, 2012 at 6:16
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.