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

404
Vistas
Show/hide div or image when scrolling

Is there a way to show an image or a div when scrolling down a web page and hide it when not scrolling and vice versa?

So in the code below the red div would be displayed when not scrolling, and the green div would be displayed only when scrolling.

.square {
  position: fixed;
  width: 100px;
  height: 100px;
}

.green {
  background: green;
  display: none;
}

.red {
  background: red;
}

.container {
  width: 100%;
  height: 3000px;
}
<div class="container">
  <div class="square green"></div>
  <div class="square red"></div>
</div>

The end goal is to achieve something like this: https://mailchimp.com/annual-report/ where the character appears to be walking when the user scrolls, and stands still when the user stops. Is this easily achievable?

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

0

You just need an eventListener that listen to a scroll event. However this has the issue that it only recoginze when you scroll but not when you stop scrolling. For that you can use this answer that explains how to listen for a "scroll-stop"

To make the code shorter and easier, I removed your display: none from the green box. I added a new class d-none that contains this proeprty now instead. By default it is added to the green box.

With classList.toggle('d-none') I can toggle class within both boxes which makes it easier then to address and then add or remove the class for every box on its own.

var timer = null;
var box = document.querySelectorAll('.square');
window.addEventListener('scroll', function() {
  if (timer !== null) {
    clearTimeout(timer);
  } else {
    box.forEach(el => el.classList.toggle('d-none'));
  }
  timer = setTimeout(function() {
    box.forEach(el => el.classList.toggle('d-none'));
  }, 150);
}, false);
.d-none {
  display: none;
}

.square {
  position: fixed;
  width: 100px;
  height: 100px;
}

.green {
  background: green;
  /* display: none; */
  /* removed */
}

.red {
  background: red;
}

.container {
  width: 100%;
  height: 3000px;
}
<div class="container">
  <div class="square green d-none"></div>
  <div class="square red"></div>
</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