I am working on a project where I move an element (dot) around with sliders or drag and drop, I would like to costrain the drag and drop to it’s parent element? here is the code on codepen; https://codepen.io/editor/Julian-Evans/pen/01a154f3-f5c8-78b0-b2fd-78adddce60bf
Welcome ![]()
You have an excellent starting point, and can just add a little bit of logic to the mouseMove function to constrain the dot:
function mouseMove(e) {
newX = startX - e.clientX
newY = startY - e.clientY
startX = e.clientX
startY = e.clientY
dot.style.top = (dot.offsetTop - newY) + 'px'
dot.style.left = (dot.offsetLeft - newX) + 'px'
let nX = dot.offsetLeft - 196
let nY = dot.offsetTop - 146
r.style.setProperty('--xVal', nX);
r.style.setProperty('--yVal', nY);
let Lh = Math.hypot(nX, nY)
r.style.setProperty('--LHeight', Lh)
let AnG = Math.atan2(nY, nX) * (180 / Math.PI);
console.log({ nX, nY })
console.log({ AnG })
value.innerHTML = nX + "px";
value.textContent = nX + "px";
slider.value = nX
value2.innerHTML = nY + "px";
value2.textContent = nY + "px";
slider2.value = nY
}
That code is responsible for:
- updating the dot position
- updating the sliders
So, add limits to the values. You have everything you need there.
Is there something in particular you are struggling with?
Thanks Sky020, I am fairly new to JavaScript, I’ve been mainly learning CSS for the past couple of years. I tried limiting the x value using min function, but I couldn’t get that to work, in Vba I would use “if x > 195 then exit sub”, is this possible in JavaScript or should I use “removeEventListener()”?
This is working;

