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

176
Vistas
Can not change style of html element assigned to variable in a function

I am working on a pong in browser and I'm having some problems with things not working as expected

Basically, I need this to work:

let grid = document.getElementById('grid');
let ball; //declared outside of function as global variable

function setup() {
    grid.innerHTML += '<div id="ball"></div>'; //this works
    ball = document.getElementById("ball");
    ball.style.width = "10px"; //this works
    ball.style.height = "10px"; //this works
}

function moveBall(x, y) {
    alert(ball.width); //outputs 10px
    ball.style.left = x + "px"; //doesn't do anything
    ball.style.top = y + "px"; //doesn't do anything
}

setup();
moveBall(20, 20);

In the function moveBall, I can get the width for example from the ball, but I can not change the width. I can however change the width if I the function like this:

function moveBall(x, y) {
    ball = document.getElementById("ball");
    alert(ball.width); //outputs 10px
    ball.style.left = x + "px"; //doesn't do anything
    ball.style.top = y + "px"; //doesn't do anything
}

I hope this is clear, I've been looking for a reason for this behaviour for hours but can't seem to find a fix. Please help :) (also, ignore how to code might not make sense since I cut down a lot of it which doesn't affect this problem).

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Thanks for the effort you put in! What you made does seem to work but if I combine it with the other code I wrote, it doesn't work anymore. This is what my setup actually looks like, and something in there is making it not work.

    function setup() {
        grid.innerHTML += '<div id="ball"></div>';
        ball = document.getElementById("ball");
        ball.style.width = BALLWIDTH + "px";
        ball.style.height = BALLHEIGHT + "px";

        grid.innerHTML += '<div id="player1"></div>';
        player1 = document.getElementById("player1");
        player1.style.width = PLAYERWIDTH + "px";
        player1.style.height = PLAYERHEIGHT + "px";
        player1.style.right = DISTANCEFROMWALL + "px";

        grid.innerHTML += '<div id="player2"></div>';
        player2 = document.getElementById("player2");
        player2.style.width = PLAYERWIDTH + "px";
        player2.style.height = PLAYERHEIGHT + "px";
        player2.style.left = DISTANCEFROMWALL + "px";
    }
about 4 years ago · Juan Pablo Isaza Denunciar

0

It is working fine on my side.

Possible Reason

The thing is, width is a string when fetching using style. You have to get width in number/float and add the desired width number to it. Then, you have to add px string normally and everything will work as expected.

let grid = document.getElementById('grid');
let ball;

function setup() {
    grid.innerHTML += '<div id="ball"></div>'; 
    ball = document.getElementById("ball");
    ball.style.width = "10px";
    ball.style.height = "10px"; 
}

//this is working fine for me
function moveBall(x, y) {
    ball.style.position = "absolute"; //<-- add position absolute
    ball.style.width = parseInt(ball.style.width.slice(0,-2))+10+'px';
    ball.style.height = parseInt(ball.style.height.slice(0,-2))+10+'px';
    ball.style.left = x + "px"; 
    ball.style.top = y + "px"; 
}

setup();


let x = 0, y =0;
setInterval(() => {
  x += 20;
  y += 10;
  moveBall(x, y);
},1000);
#grid{
  width:100vw;
  height:100vh;
  background-color: black;
}

#ball{
  border-radius: 50%;
  background-color: white;
  transition: all 0.3s ease;
}
<html>
  <body>
    <div id="grid"></grid>
  </body> 
</html>

about 4 years ago · Juan Pablo Isaza 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