Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

397
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!