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

196
Vistas
Why the randomize function for absolute margin is not working?

I have a HTML and I'm trying to randomize each layer top margin attribute.

function randomize() {
  let r;
  let list = document.querySelectorAll("span");
  for (let i = 0; i < list.length; i++) {
    r = Math.floor(Math.random() * 50);
    list.forEach((list) => {
      style.top = `${r} + px`;
    });
  }
}
span {
  position: absolute;
  height: 20px;
  width: 20px;
  border-radius: 100%;
  z-index: -2;
}
<div class="parallax">
  <span class="layer" data-speed="-5">10110</span>
  <span class="layer" data-speed="-5">0</span>
</div>

What am I getting wrong here? I can't find the proper solution.

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

0

Because <span> is natively an inline element, and margin has no effect.

Change your <span>s to <div>s.

about 4 years ago · Juan Pablo Isaza Denunciar

0

A few things:

  1. To use the top CSS property, the element needs to have a position defined. You can set that in the CSS (position: relative) or set it in the JS. (EDIT OP added CSS that they had already which set the position. Leaving this here for people that use top without setting an element's position)
  2. You need to move the randomization into the forEach otherwise it will have the same value for all span elements
  3. You need to attach the style prop to the element you are passing in the forEach, e.g., list.style.styleProp

function randomize() {
  let r;
  let list = document.querySelectorAll("span");
  for (let i = 0; i < list.length; i++) {
    list.forEach((list) => {
      r = Math.floor(Math.random() * 50);
      list.style.top = r + 'px';
    });
  }
}

randomize();
span {
  position: absolute;
  height: 20px;
  width: 20px;
  border-radius: 100%;
  z-index: -2;
}
<div class="parallax">
  <span class="layer" data-speed="-5">10110</span>
  <span class="layer" data-speed="-5">0</span>
</div>

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