Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
How can I augment the margin of an element from the Dom in my script?

I'm trying to move the button through the body using arrows. It's wrong to put numeric literals, and I tested that the code it's linked to the HTML.

document.body.addEventListener("keydown", function (evt) {
    
    const btn = document.querySelector('button');
    switch(evt.code) {
        
        case 'ArrowUp':
            btn.style.marginBottom =+ 10;
        break;

        case 'ArrowDown':
            btn.style.marginTop =+ 10;
        break;

        case 'ArrowRight':
            btn.style.marginLeft += 10;
        break;

        case 'ArrowLeft':
            btn.style.marginRight =+ 10;
        break;

        default:

    }
}) 
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

marginLeft and other return a string (with "px" text), so you have to remove it in order to make sum.

document.body.addEventListener("keydown", function (evt) {
    
    const btn = document.querySelector('#mybutton');
 
    switch(evt.code) {
        
        case 'ArrowUp':
            btn.style.marginTop = (parseInt(btn.style.marginTop.replace("px","")) - 10) + "px";
        break;

        case 'ArrowDown':
        btn.style.marginTop = (parseInt(btn.style.marginTop.replace("px","")) + 10) + "px";
        break;

        case 'ArrowRight':
        btn.style.marginLeft = (parseInt(btn.style.marginLeft.replace("px","")) + 10) + "px";
        break;

        case 'ArrowLeft':
                btn.style.marginLeft = (parseInt(btn.style.marginLeft.replace("px","")) - 10) + "px";

        break;

        default:

    }
}) 
<div>before</div>
    <button id="mybutton" style="margin:1px">hello</button>
    <div>after</div>

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda