Setting boundries
You may have noticed that you can move a card off the screen to the top and left. Let's set some boundries so that doesn't happen.
As we continue adding helper methods, we'll begin building functions in a separate folder called utils.js
, so thats where we will add the following function.
Create setNewOffset
function in src/utils.js
This method will be responsible for setting the final x
& y
position of our card. to do so, we will reference the cards top
and left
position, as well as the current mouse move.
By checking the final offset values, we will ensure that these values never fall below -1
in either direction, ensuring that the farthest our notes can be moved to the top and left is 0
.
export const setNewOffset = (card, mouseMoveDir = { x: 0, y: 0 }) => {
const offsetLeft = card.offsetLeft - mouseMoveDir.x;
const offsetTop = card.offsetTop - mouseMoveDir.y;
return {
x: offsetLeft < 0 ? 0 : offsetLeft,
y: offsetTop < 0 ? 0 : offsetTop,
};
};
With this new method, we can import it into our NoteCard
component, and now use this inside of our mouseMove
function
import {setNewOffset} from '../utils.js'
//...
const mouseMove = (e) => {
let mouseMoveDir = {
x: mouseStartPos.x - e.clientX,
y: mouseStartPos.y - e.clientY,
};
mouseStartPos.x = e.clientX;
mouseStartPos.y = e.clientY;
const newPosition = setNewOffset(cardRef.current, mouseMoveDir);
setPosition(newPosition);
};