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

210
Visualizações
JavaScript change element position on keyboard button press

So I want to change element's position by 100 on keyboard button press.
My code:

document.addEventListener("keypress", (event) => {
    var keyName = event.key;
    if (keyName == "s") {
        console.log(keyName);
        document.getElementById("element").style.top + 100;
    };
}, false);
<div id="element">•</div>

And the only thing the code does, is sending log to console about pressed key.

EDIT: The element's position is already Absolute

position: absolute;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

To achieve what you are trying you have to do the folowing:

  1. Your element must be position: absolute or position: relative
  2. the style.top properie is a setter so you have to set it´s value like style.top = '100px'
  3. the top value is a string to add 100 on top you need to parse it to a string and then add back the 'px' at the end of the string

document.addEventListener("keypress", (event) => {
    const elementToMove = document.getElementById("element");
    var keyName = event.key;
    if (keyName == "s") {
        elementToMove.style.top = (parseInt(elementToMove.style.top || 0) + 100)+'px';
    };
}, false);
<div id="element" style="position: absolute;">•</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

The top CSS property participates in specifying the vertical position of a positioned element. It has no effect on non-positioned elements. Make sure your element is positioned (absolute, relative, fixed, static etc...).

Your code is buggy here: document.getElementById("element").style.top + 100; there should be an assignment to element (+100) will not work.

if you want to add margin then do the following: document.getElementById("element").style.marginTop = "100px";

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