JSFiddle - React, Tailwind, and code Playground

by levchenko_d

HTML

<script src="https://beat.today/javascripts/functions.js"></script>
<div class="draggable"></div>

CSS

div{
  position: absolute;
  width: 50px;
  height: 50px;
  background: #00b0ef;
}

div.drag-end{
  background: red;
}

div.drag-move{
  background: green;
  border-radius: 7px;
}

body{
  min-height: 100vh;
}

JavaScript

//attach events
Element.prototype.on = function(object){
  var t = this;
  App.forIn(object, function(key, value){
    t.addEventListener(key, value);
  });
};
//detouch events
Element.prototype.off = function(object){
  var t = this;
  App.forIn(object, function(key, value){
    t.removeEventListener(key, value);
  });
};

/*------- Drag -------

Usage example:

var draggableInstance = new Drag({
	selector: '.draggable',
  ondrag: function(e){},
  ondragend: function(e){}
});
*/

var Drag = function(options){
	var t = this;
  
  t.o = options;
  t.element = App.q(t.o.selector);
  if(t.element){
  	 t.startPosition = t.element.position();// x,y
  	 t.position = t.element.position();// x,y
  	 t.cursor = {x:0,y:0};
     t.attachEvents();
  }
};

Drag.prototype.dragStart = function(e){
	var t = this;
  t.cursor.x = e.pageX;
  t.cursor.y = e.pageY;

  t.element.addClass('drag-start');
};

Drag.prototype.dragMove = function(e){
	var t = this; 
  t.element.addClass('drag-move');
  t.element.style.left = t.position.x + (e.pageX-t.cursor.x) + 'px';
  t.element.style.top = t.position.y + (e.pageY-t.cursor.y) + 'px';
  App.isFn(t.o.ondrag)(e);
};

Drag.prototype.dragEnd = function(e){
	var t = this; 
  t.position = t.element.position();
  t.element.removeClass('drag-start drag-move');
  App.isFn(t.o.ondragend)(e);
};

Drag.prototype.attachEvents = function(){
	var t = this,
  		Body = document.body,
      events = {};
  
  t.handleDragMove = function(e){
		t.dragMove(e);
  };
  
  t.handleDragEnd = function(e){
		t.dragEnd(e);
    Body.off(events);
  };
  
  t.handleDragStart = function(e){
  	t.dragStart(e);
    Body.on(events);
  };
  
  events = {
    'mousemove': t.handleDragMove,
    'mouseup': t.handleDragEnd,
    'touchmove': t.handleDragMove,
    'touchend': t.handleDragEnd
  };
  
  t.element.on({
  	'mousedown': t.handleDragStart,
    'touchstart': t.handleDragStart
  });
};

/*------- Drag END -------*/

var draggableInstance = new Drag({
	selector:...