JSFiddle - React, Tailwind, and code Playground

by Henry

HTML

<div id="container" style="overflow:scroll">
  <div id="box">
    <span>DRAG ME</span>
    <div id="dragger"></div>
  </div>
</div>

CSS

#container{
  position: relative;
  width: 200px;
  height: 200px;
  border: solid 1px black;
  background-color: white;
  -webkit-font-smoothing: antialiased;
  -webkit-user-select: none;
}
#box{
  position: absolute;
  border-right: 100px solid transparent; /* changed this */
  border-bottom: 100px solid transparent; /* changed this */
  outline: 1px solid red; /* just for demo purposes */
  pointer-events: none; /* click through (no IE<9, no Opera Mini) */
  
  width: 80px;
  height: 80px;
  left: 50px;
  top: 50px;
  text-align: center;
  vertical-align: middle;
  line-height: 80px;
  font-family: Calibri;
  font-size: 14px;
  font-weight: bold;
}
#box span {
  position: relative;
  z-index: 1;
}
#box:before,
#dragger {
  content: '';
  position: absolute;
  z-index: 0;
  width: 80px;
  height: 80px;
  left: -2px;
  top: -2px;
  border: solid 2px #666;
  border-radius: 10px;
  background: #ccc;
  cursor: move;
  cursor: grab;
  cursor: -webkit-grab;
}
#dragger {
  background: none;
  border: 0;
  z-index: 2;
}
#dragger:active{
  cursor: move;
  cursor: grabbing;
  cursor: -webkit-grabbing;
}

JavaScript

var box = document.getElementById("box");
var dragger = document.getElementById("dragger");
dragger.addEventListener("mousedown", function(e){
	var X_init = e.clientX, Y_init = e.clientY;
	var left_init = box.offsetLeft;
  var top_init = box.offsetTop;
	var cur_left = function(e){
		var left = left_init+e.clientX-X_init;
		return (left>10?left:10);
	}
	var cur_top = function(e){
		var top = top_init+e.clientY-Y_init;
    return (top>10?top:10);
  }
	var drag_func = function(e){
  	box.style.left = cur_left(e)+"px";
    box.style.top = cur_top(e)+"px";
  };
	document.addEventListener("mousemove", drag_func);
	document.addEventListener("mouseup", function(e){
		document.removeEventListener("mouseup", arguments.callee);
		document.removeEventListener("mousemove", drag_func);
	});
});