Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
Moving element to specific css coordinates (top and left) not working using javascript

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 :)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!