Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda