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

244
Vistas
HTML element "top" style being set generated random number but not moving to the position in JavaScript

I have been working on a project and remaking snake. The code is all supposed to set the position of the apple to a random number and it logs it as doing so, but the apple stays in the same place. The position type is "relative" so it stays within a box. This is my first time using HTML and Javascript together. The code just doesn't work (no errors or warnings). The random number generation code is as follows:

function rand(min, max, step) {
    var delta,
        range,
        rand;
    if (arguments.length < 2) {
        max = min;
        min = 0;
    }
    if (!step) {
        step = 1;
    }
    delta = max - min;
    range = delta / step;
    rand = Math.random();
    rand *= range;
    rand = Math.floor(rand);
    rand *= step;
    rand += min;
    return parseInt(rand);
}

The code for setting the "apples" position (in js):

function generateApple() {
    let y = parseInt(rand(-15, 470, 15))
    apple.style.top = y
    console.log(apple.style.top)
}

It does successfully print the new location but doesn't move the "apple" HTML object to the position. I have the initial position set to 15 in style.left and 15 in style.top. The CSS for the apple is as follows:

.apple {
    height: 15px;
    width: 15px;
    background-color: red;
    border: 2px;
}

The code that sets the position as relative when the window loads is as follows

window.addEventListener('load', () => {
    snake.style.position = 'relative';
    apple.style.position = 'relative'
    snake.style.left = 105;
    snake.style.top = 105;
    apple.style.top = 15;
    apple.style.left = 15;
    if (highScore == null) {
        window.localStorage.setItem('high_score', 0)
    }
});

The full code is on this website: https://passionproject.on.fleek.co

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Window load event is fired after the JavaScript that is positioning the apple has been run. If you put could breakpoints in your code, you will see that first it moves the apple into the right position and then the load event listener fires.

Since your JS is at the bottom of the page, the simplest fix really is to not use load event listener and just do it immediately.

about 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