How to change the opacity while scrolling

In this tutorial, we will learn how to change the opacity while scrolling using CSS. You must have seen ads on various websites that disappear as soon as you scroll down.

So let’s begin with this tutorial. So this might not seem less than magic to you until I tell you this is possible. We can do this with the help of jQuery and CSS. jQuery is used to control the opacity of the page while scrolling.

Code to change the opacity while scrolling using CSS

opacity.html file

<!DOCTYPE html>
  <title>Change opacity on scroll</title>
  <link href="style.css" rel="stylesheet" type="text/css">
  <script src=""></script>
  <script type="text/javascript">
        if($(this).scrollTop() > 100){
          $(".topbar").css({"opacity" : "0"})
        else {
          $(".topbar").css({"opacity" : "1"})
  <div class="topbar">

style.css file

  margin: 0;
  padding: 0;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100px;
  background: black;
  transition: .5s;
  width: 100%;
  height: 100vh;


We have used the scroll function of jQuery which is the in-built function. All we do is just get the current scroll position of the window, we then find out what percentage of the element in question is now off-screen, and set its opacity with that percentage.

We use external styling to link the CSS file to our HTML file. The link tag is used under the head tag. Section tag is a little way different from division tag. <Section> tag creates a section for the document like headers, footers, chapters or any other section.

Then we obtain the current scroll value with the help of scrollTop() function. When we get the scroll value we check if this is greater than the 100 percent of the scroll value. If it is so then we set the opacity of the text to zero. It just means that the whole image is scrolled. If the scroll value is not to its full value then we set the opacity to zero.

I hope you understood the code well. Feel free to ask your doubts in the comments section below.

You may also read,

One response to “How to change the opacity while scrolling”

  1. Mlaksi says:

    Thank you Ive literally been struggling to find way to do something like this whole day learning about transparent navbars and other b***sh** this was so helpful I was getting mad

Leave a Reply

Your email address will not be published. Required fields are marked *