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);
\$\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 );

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.