Skip to content

Instantly share code, notes, and snippets.

@gabrielstuff
Created May 17, 2013 23:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gabrielstuff/5602500 to your computer and use it in GitHub Desktop.
Save gabrielstuff/5602500 to your computer and use it in GitHub Desktop.
Using jquery to make a masked element draggable.
/*from http://css-tricks.com/snippets/jquery/draggable-without-jquery-ui/
Added compatibility with iOS touch devices
HTML should be something like :
<div class="container">
<img id="image1" class="erb-image-wrapper" src="test.jpg"> <!-- this is your masked element -->
<img id="image2" class="erb-image-wrapper" src="femme.png" style="cursor: move;"> <!-- this is your mask over the masked element-->
</div>
*/
(function($) {
$.fn.drags = function(opt) {
opt = $.extend({
handle: "",
cursor: "move"
}, opt);
isTouch = function(reset) {
if (typeof(Modernizr) !== 'undefined') return Modernizr.touch;
if ('ontouchstart' in window || (window.DocumentTouch && document instanceof DocumentTouch)) {
return true;
} else {
return false;
}
};
if (opt.handle === "") {
var $el = this;
} else {
var $el = this.find(opt.handle);
}
return $el.css('cursor', opt.cursor).bind("mousedown touchstart", function(ev) {
if (opt.handle === "") {
var $drag = $(this).prev().addClass('draggable');
} else {
var $drag = $(this).prev().addClass('active-handle').parent().addClass('draggable');
}
var z_idx = $drag.css('z-index'),
drg_h = $drag.outerHeight(),
drg_w = $drag.outerWidth(),
curX = (isTouch() ? ev.originalEvent.touches[0].pageX : ev.pageX),
curY = (isTouch() ? ev.originalEvent.touches[0].pageY : ev.pageY),
pos_y = $drag.offset().top + drg_h - curY,
pos_x = $drag.offset().left + drg_w - curX;
$drag.css('z-index', -1).parents().bind("mousemove touchmove", function(ev) {
var curX = (isTouch() ? ev.originalEvent.touches[0].pageX : ev.pageX),
curY = (isTouch() ? ev.originalEvent.touches[0].pageY : ev.pageY);
$('.draggable').offset({
top: curY + pos_y - drg_h,
left: curX + pos_x - drg_w
}).bind("mouseup touchend", function() {
$(this).prev().removeClass('draggable').css('z-index', z_idx);
});
});
ev.preventDefault(); // disable selection
}).bind("mouseup touchend", function(ev) {
if (opt.handle === "") {
$(this).prev().removeClass('draggable');
} else {
$(this).prev().removeClass('active-handle').parent().removeClass('draggable');
}
ev.preventDefault();
});
}
})(jQuery);
$("#image2").drags();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment