Advertisement
Guest User

Draggable without jQuery UI and with touch events support

a guest
Oct 10th, 2013
1,046
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // thanks once again to chris coyer for this wonderful snippet
  2. // edited to support touch events
  3. // www.riccardolardi.ch
  4. // http://css-tricks.com/snippets/jquery/draggable-without-jquery-ui
  5.  
  6. (function($) {
  7.  
  8.     $.fn.drags = function(opt) {
  9.  
  10.         opt = $.extend({
  11.             handle:""
  12.         }, opt);
  13.  
  14.         if(opt.handle === "") {
  15.             var $el = this;
  16.         } else {
  17.             var $el = this.find(opt.handle);
  18.         }
  19.  
  20.         return $el.on("mousedown touchstart", function(e) {
  21.  
  22.             if(opt.handle === "") {
  23.                 var $drag = $(this).addClass('draggable');
  24.             } else {
  25.                 var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
  26.             }
  27.  
  28.             var z_idx = $drag.css('z-index'),
  29.                 drg_h = $drag.outerHeight(),
  30.                 drg_w = $drag.outerWidth(),
  31.                 pos_y = $drag.offset().top + drg_h - e.pageY || $drag.offset().top + drg_h - e.originalEvent.pageY,
  32.                 pos_x = $drag.offset().left + drg_w - e.pageX || $drag.offset().left + drg_w - e.originalEvent.pageX;
  33.  
  34.             $drag.css('z-index', z_idx).parents().on("mousemove touchmove", function(e) {
  35.  
  36.                 $('.draggable').offset({
  37.                     top: e.pageY  + pos_y - drg_h || e.originalEvent.pageY + pos_y - drg_h,
  38.                     left: e.pageX + pos_x - drg_w || e.originalEvent.pageX + pos_x - drg_w
  39.                 }).on("mouseup touchend touchcancel", function() {
  40.                     $(this).removeClass('draggable');
  41.                 });
  42.  
  43.             });
  44.  
  45.             e.preventDefault();
  46.  
  47.         }).on("mouseup touchend touchcancel", function() {
  48.  
  49.             if(opt.handle === "") {
  50.                 $(this).removeClass('draggable');
  51.             } else {
  52.                 $(this).removeClass('active-handle').parent().removeClass('draggable');
  53.             }
  54.  
  55.         });
  56.  
  57.     }
  58.    
  59. })(jQuery);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement