'Need a Click and Drag solution using Vanilla Javascript without jQuery
I have to do a click-and-drag solution for a background image in Vanilla Javascript for a project. I found this solution using jQuery in Codepen. Can anyone help me with a Vanilla Javascript version of it?
Draggable.create(".box", {
bounds:$container,
edgeResistance:0.65,
type:"x,y",
throwProps:true,
autoScroll:true,
});
https://codepen.io/johndownie/pen/vxOwrx
The project is going to be in Vue but if I can get a solution in plain HTML, CSS and Javascript, it will be great.
Solution 1:[1]
You can go with this approach. It is not as smooth as jquery draggable.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body,
html {
height: 100%;
width: 100%;
}
body {
background-color: black;
}
#container {
background-color: #333;
height: 100%;
width: 100%;
overflow: hidden;
position: relative;
}
#box {
background-image: url(http://www.vgmaps.com/NewsArchives/April2005/LegendOfZelda-Link%27sAwakeningAdvance-Koholint.png);
background-size: 100%;
background-position: center;
width: 100%;
height: 100%;
position: absolute;
}
#box:hover {
cursor: move;
}
</style>
</head>
<body>
<div id="container">
<div id="box"></div>
</div>
</body>
<script>
dragElement(document.getElementById("container"));
function dragElement(elmnt) {
var pos1 = 0,
pos2 = 0,
pos3 = 0,
pos4 = 0;
if (document.getElementById("box")) {
/* if present, the header is where you move the DIV from:*/
document.getElementById("box").onmousedown =
dragMouseDown;
} else {
/* otherwise, move the DIV from anywhere inside the DIV:*/
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = elmnt.offsetTop - pos2 + "px";
elmnt.style.left = elmnt.offsetLeft - pos1 + "px";
}
function closeDragElement() {
/* stop moving when mouse button is released:*/
document.onmouseup = null;
document.onmousemove = null;
}
}
</script>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sumit Sharma |