I have a draggable element with id mydiv that is contained within another element with id container. I want to restrict the movement of mydiv so that it stays inside the container without leaving its boundaries. How can I achieve this?
Below is the code snippet:
//Make the DIV element draggagle:
dragElement(document.getElementById("mydiv"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
/* if present, the header is where you move the DIV from:*/
document.getElementById(elmnt.id + "header").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:
var container = document.getElementById('container');
var containerRect = container.getBoundingClientRect();
var elementRect = elmnt.getBoundingClientRect();
if ((elementRect.left - pos1) >= containerRect.left &&
(elementRect.right - pos1) <= containerRect.right &&
(elementRect.top - pos2) >= containerRect.top &&
(elementRect.bottom - pos2) <= containerRect.bottom) {
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;
}
}
#container {
border: 1px solid red;
height: 300px;
width: 400px;
}
#mydiv {
position: absolute;
z-index: 9;
background-color: #f1f1f1;
text-align: center;
border: 1px solid #d3d3d3;
}
#mydivheader {
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;
}
<h1>Draggable Element</h1>
<p>Click and hold the mouse button down while moving the element</p>
<div id="container">
<div id="mydiv">
<div id="mydivheader">Click here to move</div>
<p>Move</p>
<p>this</p>
<p>element</p>
</div>
</div>
To keep the element inside the container, modifications need to be made in the elementDrag(e)
function. You can use conditional statements to ensure the element does not go beyond the container boundaries. It's important to maintain the existing code structure and use only pure JavaScript for the solution.