Skip to content

Instantly share code, notes, and snippets.

@tlync
Created October 14, 2011 10:21
Show Gist options
  • Save tlync/1286753 to your computer and use it in GitHub Desktop.
Save tlync/1286753 to your computer and use it in GitHub Desktop.
jquery-feedbackable.js
(function($) {
var hasTouch = 'ontouchstart' in window;
/**
* @param {number} [amount=2]
* @param {string} [direction=both] both, h, v
*/
$.fn.feedbackable = function(options){
var settings = $.extend({
amount: 2,
direction: 'both' // both/h/v
}, options);
var calcPixel = function(pxStr, amount){
if(pxStr === 'auto'){
pxStr = 0;
}
var num = parseInt(pxStr);
return (isNaN(num)) ? '' : num + amount + 'px';
};
var dent = function(){
var s = this.style,
pos = s.position,
amount = settings.amount,
dir = settings.direction,
isBoth = dir === 'both',
isVertical = dir === 'v' || isBoth,
isHorizontal = dir === 'h' || isBoth,
org
var apply = function(){
var $el = $(this);
org = {
position: $el.css('position'),
top: $el.css('top'),
bottom: $el.css('bottom'),
left: $el.css('left'),
right: $el.css('right')
};
if(org.position == 'static'){
$el.css({
position: 'relative',
top: isVertical ? calcPixel(0, amount) : org.top,
left: isHorizontal ? calcPixel(0, amount) : org.left
});
}else{
var isTop = org.top && org.top.indexOf('px') !== -1,
isBottom = org.bottom && org.bottom.indexOf('px') !== -1,
isLeft = org.left && org.left.indexOf('px') !== -1,
isRight = org.right && org.right.indexOf('px') !== -1;
$el.css({
top: isTop && isVertical ? calcPixel(org.top, amount) : org.top,
bottom: isBottom && isVertical ? calcPixel(org.bottom, -amount) : org.bottom,
left: isLeft && isHorizontal ? calcPixel(org.left, amount) : org.left,
right: isRight && isHorizontal ? calcPixel(org.right, -amount) : org.right
});
}
};
var revert = function(){
if(!org) return;
$(this).css({
position: org.position,
top: org.top,
bottom: org.bottom,
left: org.left,
right: org.right
});
org = null;
};
var start = hasTouch ? 'touchstart' : 'mousedown',
end = hasTouch ? 'touchend' : 'mouseup mouseout';
$(this).bind(start, apply).bind(end, revert);
};
this.each(dent);
return this;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment