Skip to content

Instantly share code, notes, and snippets.

@RupGautam
Created February 9, 2018 23:12
Show Gist options
  • Select an option

  • Save RupGautam/36816b5cadd41e0cbd05957809279d3d to your computer and use it in GitHub Desktop.

Select an option

Save RupGautam/36816b5cadd41e0cbd05957809279d3d to your computer and use it in GitHub Desktop.
Draggable with Javascript

Draggable with Javascript

#Draggable with JavaScript Draggable div using only plain javascript . Touch event is now added ; ) . Feel free to fork it &improv it and also tell me what new thing you added, I loved to see it :) .

A Pen by Rup Gautam on CodePen.

License.

<div id='dragme'>
</div>
onload = adding;
//==> Define the Variables <==
var body = document.body;
var dragme = document.getElementById('dragme');
var cs = dragme.style ;
//==> Add Some Event Listener for Mouse & Touch <==
function adding()
{
dragme.addEventListener('mousedown',hold,false);
body.addEventListener('mouseup',release,false);
}
//==> On Hold Function <==
function hold()
{
dragme.addEventListener('mousemove',move,true);
body.addEventListener('mousemove',move,true);
dragme_t.addEventListener('touchmove',tmove,true);
body_t.addEventListener('touchmove',tmove,true);
}
//==> On Realease Function <==
function release()
{
dragme.removeEventListener('mousemove',move,true);
body.removeEventListener('mousemove',move,true);
dragme.style.background = "#00ff00";
}
//==> On Mousemove Function <==
function move(event){
var epY = event.clientY;
var epX = event.clientX;
cs.position = "absolute";
cs.top = epY + "px";
cs.left = epX + "px";
}
html, body{
width:100%;
height:100%;
}
#dragme{
margin: 0 auto;
position: relative;
width:150px;
height:150px;
top:30%;
background: #05041e;
border-radius: 15px;
border: outset 5px #42c8f4;
cursor: move;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment