Reputation: 1042
I need your help. I have draggable Note which is now draggable anywhere on the screen... I need to prevent it to be draggable only max at corners of the screen. I put on screen what I need to do ...
I need it like this one:
So in every case, there should be able to see all sides of my Node.
I really don't know ho to do it properly I tried something like this:
onMouseMove(e) {
if (!this.state.dragging) return;
const newX = e.pageX - this.state.cursorPosX;
const newY = e.pageY - this.state.cursorPosY;
if (this.controlPositionOfNode(newX, newY)) {
this.setState({
posX: newX,
posY: newY,
});
}
e.stopPropagation();
e.preventDefault();
}
controlPositionOfNode(newX: number, newY: number) {
if (newX < 0 || newX > window.innerWidth) {
return false;
}
if (newY < 0 || newY > window.innerHeight) {
return false;
}
return true;
}
But this is not so smooth as I would like to have it. Thx for your help
Here is full code on codeSandbox: https://codesandbox.io/s/throbbing-moon-oxzpp?file=/src/App.js
Edit okay I made some progress and now I am missing only last thing. I don't know how to get My element width and height. (It is resizable element bcs. textarea)
Upvotes: 1
Views: 5243
Reputation: 1242
You need to define the size of your dialog window and then you can check the position in onMouseMove like this:
onMouseMove(e) {
if (!this.state.dragging) return;
let x = e.pageX - this.state.rel.x;
let y = e.pageY - this.state.rel.y;
if (x < 0 || x > window.innerWidth - this.state.dialogWidth) {
x = x < 0 ? 0 : window.innerWidth - this.state.dialogWidth;
}
if (y < 0 || y > window.innerHeight - this.state.dialogHeight) {
y = y < 0 ? 0 : window.innerHeight - this.state.dialogHeight;
}
this.setState({
x: x,
y: y
});
e.stopPropagation();
e.preventDefault();
}
See full example: https://codesandbox.io/s/laughing-roentgen-t4umr
Upvotes: 2