Binding touch events and moving an element 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 &gt;= limit) {
        move = limit;
    } else if (difference &lt;= 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 &gt;= limit) {
        move = limit;
    } else if (difference &lt;= 0) {
        move = 0;
    } else {
        move = difference;
    }

    if (threshold &gt; (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);
Could you write something like this?

var limited = function( value, limit ){
    if (value &gt;= limit) { 
        return limit; 
    } else if (value &lt;= 0) { 
        return 0; 
    } else { 
        return value; 
    } 
}


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