We can use two methods to determine where to place the preview.
Using the gaps between elements
Using the elements
Determine preview position with the gaps
We can position the preview according to the gaps between elements.
Here’s a picture of what this means.
If the user drags the original element between the left of the dropzone and the middle of the first element, we put them in position 1.
If the user drags the original element between the middle of first element and the middle of second element, we put them in position 2.
And so on…
Unfortunately, the gap method isn’t suitable for responsive design. You need to create two extra positions (the leftmost one and the rightmost one) per now.
We need to use another method that makes sense.
Determine preview position with the elements
We can position the preview when the dragged element lands on another element. Here’s a picture of what this means:
This method works with responsive design because we don’t have to worry about the number of rows we have.
Getting preview positions
Let’s start by creating a function called getPreviewPositions. This function returns an array of possible positions.
It helps to draw the positions on screen so we can see we’re using the correct positions. To do this, we can create an extra <div> for each position.
Next, we need to know if the user dragged the original element over a preview position.
If the top-left corner of the dragged element falls inside the top, right, bottom, and left boundaries of a preview position, we know the user dragged the original element into a preview position. We want to get the index of this preview position.
function move (event) {
// ...
const position = positions.findIndex(pos => {
return (pos.left < left && left < pos.right) &&
(pos.top < top && top < pos.bottom)
})
console.log(position)
}
Here are the position values:
-1 when the dragged element is not in any box
0 when user drags element onto first box
1 when user drags element onto second box
2 when user drags element onto third box
And so on…
Moving the preview element
We don’t need to do anything if position is -1. Here, we end the function with an early return.
function move (event) {
// ...
if (position === -1) return
}
But we need to move the preview element in other cases.
First, we need to mark the element that’s in the current target position.