r/learnjavascript • u/abrewchocolatecoffee • 5d ago
code help making draggable divs
why this code works:
html
<div id="box">Drag me</div>
js
const box = document.getElementById("box");
let isDragging = false;
let offsetX, offsetY;
box.addEventListener("mousedown", (e) => {
isDragging = true;
// distance from mouse to top-left corner of div
offsetX = e.clientX - box.offsetLeft;
offsetY = e.clientY - box.offsetTop;
box.style.cursor = "grabbing";
});
document.addEventListener("mousemove", (e) => {
if (!isDragging) return;
box.style.left = e.clientX - offsetX + "px";
box.style.top = e.clientY - offsetY + "px";
});
document.addEventListener("mouseup", () => {
isDragging = false;
box.style.cursor = "grab";
});
and this does not
html:
<div class="welcome_tab" id="welcome_tab_id">
<div class="welcome_tab_header" id="welcome_tab_header_id">Handle</div>
<div class="welcome_tab_body">
<div class="welcome_tab_heading">
<div class="welcome_tab_h1_pixelos"><h1>PixelOS</h1></div>
<div>
<img
src="images/pixel_heart.png"
alt="an image of a pixelated pixel_heart"
/>
</div>
</div>
<p>My very own operating system which is pretty pixelated.</p>
<p>Welcome to a pixelated world!</p>
</div>
</div>
js:
welcome_tab_header_id.addEventListener("mousedown", (e) => {
isDragging = true;
offsetX = e.clientX - welcome_tab_header_id.offsetLeft;
offsetY = e.clientY - welcome_tab_header_id.offsetTop;
welcome_tab_header_id.style.cursor = "grabbing";
});
document.addEventListener("mousemove", (e) => {
if (!isDragging) return;
welcome_tab_header_id.style.left = e.clientX - offsetX + "px";
welcome_tab_header_id.style.top = e.clientY - offsetY + "px";
});
document.addEventListener("mouseup", (e) =>{
isDragging = false;
welcome_tab_header_id.style.cursor = "grab";
});
and yes the css property is set to absolute
2
u/chikamakaleyley helpful 5d ago
brother you gotta put this in a codepen or something and format it, on paste proper code w markdown into the reddit post, that's prob a lot of reason that folks don't respond
We don't know what you mean by 'it works' 'doesn't work' - because that could mean anything
Regardless, this is what i see at a high level:
the first, you are taking a simple container and changing its x/y
the second, i can only assume that you try to drag the handle but you want its containing items to move along with it - and possibly the parent is set to absolute, which would be the reason nothing changes if that's what you identify as 'not working'
1
1
u/testingaurora 1d ago
You're dragging the header (welcome_tab_header_id) itself, but you actually want to drag the whole box (welcome_tab_id) using the header as the handle..
2
u/TalkCoinGames 5d ago
The id includes "/" which you can't use without quotes. You should change the IDs. "WelcomeTabId" or similar would be better.