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

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

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 Relatório

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