I am trying to move a HTML element (a puzzle piece) back to its original position on the screen after a dragEnd event, if the element is not inside a specified target zone.
I using a javascript object to represent the puzzle piece. The object contains the starting x and y for the element as well as a reference to the element itself (along with some other information). The code is below.
function dragEnd(e) {
if(selectedPiece.ele.id === "correctPiece" && selectedPiece.distanceVector < 30){
window.alert("Game End");
}
else{
console.log("returning piece: ", selectedPiece.ele.id);
console.log("to point ", selectedPiece.startX, selectedPiece.startY);
selectedPiece.ele.style.position = "absolute";
selectedPiece.ele.style.left = selectedPiece.startX;
selectedPiece.ele.style.top = selectedPiece.startY;
}
active = false;
}
Still when I drop the piece it stays wherever it was dropped.
When I look at the console it shows the element id and identifies the correct startX and startY properties. I have also tried appending "px" to the startX and startY with no luck.
Any help appreciated thanks :)
CodePudding user response:
I have tried hard coding the values and the pieces ends up moving but not to the x,y position that has been coded
Then, try this:
selectedPiece.ele.style.left = selectedPiece.startX "px";
selectedPiece.ele.style.top = selectedPiece.startY "px";
but not to the x,y position that has been coded
Secondly, make sure you understand how CSS absolute
works. From MDN's article:
The absolutely positioned element is positioned relative to its nearest positioned ancestor (i.e., the nearest ancestor that is not static).
Try making dragged element's immediate parent's position relative
.
CodePudding user response:
Try changing the immediate parents position to relative, put a border on the parent to see how the absolute positioned child is placed.