How to change opacity while scrolling the page?


In this article, we will delve into the intricacies of modifying the degree of transparency of an HTML element based on the user's scrolling activity. This technique can introduce an added layer of dynamism to your website, and can be accomplished effortlessly with a minimal amount of JavaScript or jQuery and CSS. Upon completing this guide, you will have gained a comprehensive comprehension of how to execute this effect, and possess the skill to tailor it to your exact requirements. So, let's plunge into the depths and learn how to adjust opacity while scrolling through the page!

Approach

We are going to see different approaches to change the opacity while scrolling the page. They will be as follows −

  • Using JavaScript

  • Using jQuery

Method 1: Using JavaScript

We shall employ the ensuing measures to modify the element's transparency during the process of scrolling −

  • Define the element to be affected − Initially, we will ascertain the HTML component for which we desire to modify the opacity, and allocate an identifier to it that can be utilized to select it in JavaScript.

  • Style the element − We shall employ CSS to adorn the said element and fix its position. This guarantees that the element will retain its fixed location on the display as the user scrolls.

  • Add an event listener − We shall proceed to employ JavaScript to append an event listener to the "scroll" event of the window object. Subsequently, the function will be executed every instance a user scrolls the webpage.

  • Calculate the current scroll position − Inside the function, we will use either the pageYOffset property or the document.documentElement.scrollTop property to calculate the current scroll position of the page.

  • Update the opacity − Using JavaScript we will set the style.opacity property of the selected element based on the current scroll position. We will use a simple formula to determine the opacity, such as 1 - scrollTop / 500

Example

The following block of code constructs a web page that incorporates a header section that gradually becomes less transparent as the user scrolls downward. The code accomplishes this effect by employing an assemblage of methodologies that utilize HTML, CSS, and JavaScript. The header section is fixed in position at the top of the page, with a black background color and white text color. The code also includes some text content, which is separated by several line breaks to create a large empty space between each block of content.

To alter the transparency of the header area while scrolling, the code employs a scroll event listener in JavaScript that monitors the user's position on the web page. When the user scrolls downwards, the code computes the extent of the user's scroll and modifies the header's transparency correspondingly. As the user scrolls down the web page, the header gradually loses its opacity, finally vanishing completely, thus producing a visually impactful effect that directs the user's attention towards the content of the webpage.

<!DOCTYPE html>
<html>
<head>
   <title>How to change opacity while scrolling the page?</title>
   <style>
      #content {
         position: fixed;
         top: 0;
         left: 0;
         right: 0;
         background-color: #000;
         color: #fff;
         padding: 10px;
      }
      h4 {
         margin-top: 100px;
      }
   </style>
</head>
<body>
   <div id="content">
      <p>Header content</p>
   </div>
   <h4>How to change opacity while scrolling the page?</h4>
   <p>Some content</p>
   <br />
   <br />
   <p>Some more content</p>
   <br />
   <br />
   <p>Some more content</p>
   <br />
   <br />
   <p>Some more content</p>
   <br />
   <br />
   <p>Some more content</p>
   <br />
   <br />
   <p>Some more content</p>
   <br />
   <br />
   <p>Some more content</p>
   <br />
   <br />
   <p>Some more content</p>
   <script>
      window.addEventListener("scroll", function () {
         let header = document.getElementById("content");
         let scrollTop = window.pageYOffset || document.documentElement.scrollTop;
         header.style.opacity = 1 - scrollTop / 500;
      });
   </script>
</body>
</html>

Let us now try to dissect and understand this code. This code consists of three parts

  • <body> element

  • <style> element

  • <script> element

Method 2: Using jQuery

The approach for accomplishing the task in jQuery is same to the approach we used in the JavaScript method. However, we are going to use the methods and objects provided by jQuery like $(window), $(window).scrollTop() to accomplish the same.

Example

In this following example the <body> code sets up a website that features a header with content and some additional content below. The header is given an ID of "content" and is styled using CSS, with a black background and white text. The content is arranged with some spacing using line breaks so as to increase the height of the complete page.

The <script> code establishes an event listener that monitors the location of the user's scroll on the page. As the user scrolls, the opacity of the header is changed using the jQuery library, steadily decreasing the opacity as the user moves down the page. This generates an energetic outcome where the header appears to become increasingly transparent as the user scrolls, introducing a component of responsiveness to the website.

The cumulative outcome is attained through the utilization of a sundry of HTML, CSS, and JavaScript methodologies, encompassing the utilization of a fixed placement for the header, specifying the header's background and text hues, and formulating a scroll event listener to trace the user's location on the page. Through conjoining these methodologies, the script constructs a website that is aesthetically pleasing and interactive.

<!DOCTYPE html>
<html>
<head>
   <title>How to change opacity while scrolling the page?</title>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <style>
      #content {
         position: fixed;
         top: 0;
         left: 0;
         right: 0;
         background-color: #000;
         color: #fff;
         padding: 10px;
      }
      h4 {
         margin-top: 100px;
      }
   </style>
</head>
<body>
   <div id="content">
   <p>Header content</p>
   </div>
   <h4>How to change opacity while scrolling the page?</h4>
   <p>Some content</p>
   <br />
   <br />
   <p>Some more content</p>
   <br />
   <br />
   <p>Some more content</p>
   <br />
   <br />
   <p>Some more content</p>
   <br />
   <br />
   <p>Some more content</p>
   <br />
   <br />
   <p>Some more content</p>
   <br />
   <br />
   <p>Some more content</p>
   <br />
   <br />
   <p>Some more content</p>
   <script>
      $(window).scroll(function () {
         let content = $("#content");
         let scrollTop = $(window).scrollTop();
         content.css("opacity", 1 - scrollTop / 500);
      });
   </script>
</body>
</html>

Conclusion

In summation, adjusting the level of transparency of a web element as you scroll down the page is a straightforward yet powerful method to enhance your website's dynamism. By employing either JavaScript or jQuery along with CSS, it's a cinch to devise a function that alters an element's opacity based on the current scrolling position. Whether you desire to gradually unveil a header or gently tweak the transparency of other on-page elements, this approach is an adaptable tool that can infuse an additional dimension of interactivity into your website. I trust this article has imparted you with a comprehensive grasp of how to modify opacity while scrolling, and that you will leverage this knowledge to create some truly stunning web pages.

Updated on: 28-Mar-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements