Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 13th, 2012  |  syntax: None  |  size: 1.87 KB  |  hits: 16  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Draggable div without jQuery UI
  2. var X, Y;
  3.  
  4. $(this).mousedown(function() {
  5.     $(this).offset({
  6.         left: X,
  7.         top: Y
  8.     });
  9. });
  10.  
  11. $("#containerDiv").mousemove(function(event) {
  12.     X = event.pageX;
  13.     Y = event.pageY;
  14. });
  15.        
  16. $(document).ready(function() {
  17.     var $dragging = null;
  18.  
  19.     $(document.body).on("mousemove", function(e) {
  20.         if ($dragging) {
  21.             $dragging.offset({
  22.                 top: e.pageY,
  23.                 left: e.pageX
  24.             });
  25.         }
  26.     });
  27.  
  28.  
  29.     $(document.body).on("mousedown", "div", function (e) {
  30.         $dragging = $(e.target);
  31.     });
  32.  
  33.     $(document.body).on("mouseup", function (e) {
  34.         $dragging = null;
  35.     });
  36. });
  37.        
  38. function endMove() {
  39.     $(this).removeClass('movable');
  40. }
  41.  
  42. function startMove() {
  43.     $('.movable').on('mousemove', function(event) {
  44.         var thisX = event.pageX - $(this).width() / 2,
  45.             thisY = event.pageY - $(this).height() / 2;
  46.  
  47.         $('.movable').offset({
  48.             left: thisX,
  49.             top: thisY
  50.         });
  51.     });
  52. }
  53. $(document).ready(function() {
  54.     $("#containerDiv").on('mousedown', function() {
  55.         $(this).addClass('movable');
  56.         startMove();
  57.     }).on('mouseup', function() {
  58.         $(this).removeClass('movable');
  59.         endMove();
  60.     });
  61.  
  62. });
  63.        
  64. #containerDiv {
  65.     background:#333;
  66.     position:absolute;
  67.     width:200px;
  68.     height:100px;
  69. }
  70.        
  71. $(document).ready(function() {
  72.  
  73. function endMove() {
  74. $(document).off('mousemove');
  75. }
  76.  
  77. function startMove(me) {
  78. $(document).on('mousemove', function(event) {
  79.     var thisX = event.pageX - me.width() / 2,
  80.         thisY = event.pageY - me.height() / 2;
  81.  
  82.     me.offset({
  83.         left: thisX,
  84.         top: thisY
  85.     });
  86. });
  87. }
  88.  
  89. $("#containerDiv").on('mousedown', function() {
  90.     $(this).addClass('movable');
  91.     startMove($(this));
  92. }).on('mouseup', function() {
  93.     $(this).removeClass('movable');
  94.     endMove();
  95. });
  96. });