I am making a Maps website like Google Map. I found a way to drag an image(div) to move. But I don’t want it to go beyond the screen. Once it goes beyond, the white background shows up. I want to set limit for the image so when the edge of the image hits the edge of the window, it can not move. What I want is not something to keep the image inside of a container, because the image is bigger than the window and how it worrks is moving the image around.
html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css.css">
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<div class="container">
<div class="draggable" id="dragMe">
<img src="Texture/test map.png">
</div>
</div>
</body>
css
* {
box-sizing: border-box;
}
html, body {
margin: 0;
padding: 0;
}
body {
height: 100vh;
width: 100vw;
overflow-x: hidden;
overflow-y: hidden;
}
img {
-webkit-user-drag: none;
-khtml-user-drag: none;
-moz-user-drag: none;
-o-user-drag: none;
}
.container {
align-items: center;
display: flex;
justify-content: center;
height: 100%;
width: 100%;
border: 1px solid #cbd5e0;
}
.draggable {
cursor: pointer;
position: absolute;
user-select: none;
align-items: center;
display: flex;
justify-content: center;
border: 1px solid #cbd5e0;
}
javascript
document.addEventListener('DOMContentLoaded', function () {
let x = 0;
let y = 0;
const ele = document.getElementById('dragMe');
const mouseDownHandler = function (e) {
x = e.clientX;
y = e.clientY;
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
};
const mouseMoveHandler = function (e) {
const dx = e.clientX - x;
const dy = e.clientY - y;
ele.style.top = `${ele.offsetTop + dy}px`;
ele.style.left = `${ele.offsetLeft + dx}px`;
x = e.clientX;
y = e.clientY;
};
const mouseUpHandler = function () {
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
};
ele.addEventListener('mousedown', mouseDownHandler);
});