Skip to content
Advertisement

Smart Drag Using JS?

Would it be possible to stop an element from dragging once it reaches the edge of the screen? I have been trying for the past hour with no luck. Here is my code so far:

JavaScript
JavaScript
JavaScript

I thought I could use the clientHeight and clientWidth, but so far I have been unsuccessful. Any help would be much appreciated.

Advertisement

Answer

I renamed var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;

to

xPosDiff = 0, yPosDiff = 0, xPosOld = 0, yPosOld = 0; so it were easier for me to understand them. 🙂

getBoundingClientRect() is pretty calculation heavy but I think it’s needed for your problem. From that method, you can extract the top, right, bottom, left from the element that you want to drag, and then I just compared it to 0, window.innerWidth, window.innerHeight, 0, but I also added the new X and Y difference for the cursor to that comparison. So if I predict that the new movement will make the element to cross any of the boundries (top, right…), I won’t move the element.

I had to resize #mp3Audio so it would fit inside the snippet. I also added a dashed border to better showcase the boundries.

PS. The code from W3Schools had the wrong thinking when doing the calculations IMHO, so I changed that as well. They had xPosDiff = xPosOld - e.clientX, which seems wrong because then you need to subtract that value from the old position: elmnt.offsetTop - yPosDiff. It seems backwards, where I prefer to add the difference instead. DS,

JavaScript
JavaScript
JavaScript
Advertisement