Young L.
Young L.

Reputation: 1042

How to prevent dragged item to be dragged outside of screen

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:

  1. The bottom border of NOTE can 't go outside of bottom-side-screen
  2. The right border of NOTE can 't go outside of right-side-screen
  3. The left border of NOTE can 't go outside of left-side-screen
  4. top border of NOTE can 't go outside of top-side-screen

So in every case, there should be able to see all sides of my Node. as

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

Answers (1)

Denis Stukalov
Denis Stukalov

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

Related Questions