0

I am trying to make a little project to help a friend. This is the link of the project: Project Link

I want to introduce a bulb that is lighted up on scrolling, but the problem is that I don't know how to stop it when the scrolling stops.

If I try this:

document.addEventListener("scroll", () => {
  document.body.classList.add("on");
  document.body.classList.remove("on");
});

It doesn't work, now it doesn't even is lighted up. I need a function to be called when the scrolling stops so the bulb "shuts down" only when the scrolls stops for all, but I didn't find anything on MDN Mozilla.

The source code in case you need it: source link

  • Does this answer your question? [Jquery .on('scroll') not firing the event while scrolling](https://stackoverflow.com/questions/19375636/jquery-onscroll-not-firing-the-event-while-scrolling) – JoelCrypto Nov 28 '22 at 16:15
  • @JoelCrypto, not really. I want to turn on the bulb on scrolling. That's easy, but when the scrolling stops I want the bulb to turn off. If I just do 'document.body.classList.add("on")' the bulb stays on. Try it at dan.alinpeter.repl.co. – Alin-Alexandru Peter Nov 28 '22 at 18:05

1 Answers1

1

Scrolling stops when you receive no more scroll events.
Then the question becomes how much delay is considered "Done Scrolling".

Keep in mind that the mouse triggers a lot of events and it's not advised to do anything too time consuming, like making DOM changes. Try to make the changes as direct as possible.

Managing a classList string can become annoying when your lightbulb start to have multiple classes and a simple toggle no longer works.

var delay = 500;
var lb = document.getElementById("litebulb");

document.addEventListener('scroll', toggleLitebulbOnOff);

// Once you've scrolled to the top/bottom or whatever you 
// stop getting scroll events, but you can also check for
// wheel events if you want the lightbulb to react beyond 
// scroll events.
//
//document.addEventListener('wheel', toggleBulbOnOff);

function toggleLitebulbOnOff(event) {
  clearTimeout();
  timeout = setTimeout(function() {
    lb.style.color = "white";
  }, delay);

  lb.style.color = "orange";
}
body {
  height: 1000px;
}

#litebulb {
  position: fixed;
  top: 20px;
  left: 100px;
  
  font-size: 40px;
  color: white;
  -webkit-text-stroke: 1px black;
  transition: color .5s
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">

<body>

  <i id="litebulb" class="bi bi-lightbulb-fill"></i>

</body>
fnostro
  • 4,531
  • 1
  • 15
  • 23