IMPLEMENTING CSS CHANGES ONLY DURING PAGE SCROLLING EVENT

By: Saurav

2019-03-18 21:42:00 UTC

Spec: Suppose there is a Call to action which is fixed in position on your web page (let's say it's in nav bar or just below the fixed header bar) and you want people's attention on it while they are visiting your page. In other words, you want it to pop out (not that stack pop)

For example, when they are scrolling you want to remind them that the call to action button is present. A great way to do it is to change the color of the call to action button from say, black to white, which even a color-blind customer can recognize.

Let's implement this:

Let's say we have a button with the following CSS:

base {
  position: fixed;
  top: 5px;
  width: 400px;
  height: 100px;
}

#initial {
  background: black;
  color: white;
}

Say you have wrapped this button in a div (or it could be inside a navbar/footer/sidebar etc) like this:

<div class='background'>
  <button id="initial" class='base'>See me change on scroll</button>
</div>

CSS for the div is:

.background {
  height: 1000px;
}

Now we want this button to flip while scrolling. What I mean is the background color would turn white and text would turn black. We can use the window.addEventListener('scroll', function(e) {}) property to get the button change only when a user is scrolling. When he is not, it should go back to default.

To implement this, we will use a timer to remove the new styles which have been added while scrolling. When we scroll, we will add a class and when we stop, the timer will remove it after the specified interval. If the user scrolls again, the timer is reset and so the whole waiting game starts again.

Here is the code:

window.addEventListener('scroll', function(e) {
	var timer;
	if (!$("#initial").hasClass('while-scrolling')){
     $("#initial").addClass('while-scrolling')
   }
   clearInterval(timer)
   timer = setInterval(function () {
   if ($("#initial").hasClass('while-scrolling')){
     $("#initial").removeClass('while-scrolling')
     }
   }, 2000)
})

The added CSS Class is:

.while-scrolling {
  background-color: #fff !important;
  color: black !important;
}

Mar 26 2019 13 59 01

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)