Fade In/Out Scroll Effect

As the user scrolls down the page, I have a slider that smoothly slides from right to left.

What I'm trying to achieve is for the slider to fade out when the last slide is no longer in view during downward scrolling, and fade back in as the last slide re-enters the view during upward scrolling.

For a visual example of this effect, you can check out this website.

While the slider functionality is working correctly, I'm facing challenges with the smooth implementation of the fade in/fade out animations.

https://i.sstatic.net/9bjD7.png

My approach involved storing an initial opacity value of 1 in a useRef object

const countRefOpacity = useRef(1);

Additionally, I added a wheel event listener to the window

  useEffect(() => {
    window.addEventListener("wheel", handleWheel);
    return () => {
      window.removeEventListener("wheel", handleWheel);
    };
  }, []);

The handleWheel function is responsible for adjusting the slider opacity based on the user's scrolling direction

  const handleWheel = (e) => {
    if (window.scrollY >= pan.current?.offsetTop * 2 && e.deltaY > 0) {
      countRefOpacity.current = countRefOpacity.current - 0.007;
      slider.current.style.opacity = countRefOpacity.current;
    } else if (window.scrollY < pan.current?.offsetTop * 2 && e.deltaY < 0) {
      countRefOpacity.current = countRefOpacity.current + 0.007;
      slider.current.style.opacity = countRefOpacity.current;
    }
  };

While the fade out animation appears smooth during downward scrolling, the fade in animation seems a bit sluggish during upward scrolling.

I'm seeking insights on how to optimize my code to achieve a seamless and natural fade in/fade out animation effect.

View the Codesandbox demo here

Answer №1

To achieve a smooth transition for a CSS property, consider utilizing the transition property. For example, you can specify a transition for opacity with a duration of 0.5 seconds:

transition: opacity .5s;

If I understand your query correctly, I suggest utilizing the transition property and implementing an event listener for the window's scroll event. This listener can monitor the user's scrolling behavior and adjust the opacity based on a specified point. You can set the opacity to 1 if the user scrolls before that point, and 0 otherwise. The transition property will smoothly handle the fade-in and fade-out effects without the need to calculate a delta value.

Additionally, it is advisable to utilize the scroll event instead of the wheel event. The wheel event specifically pertains to mouse wheel scrolling and may not be applicable to other forms of scrolling.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arrange the side by side display of uploaded image previews

Could someone please assist me with aligning my image upload preview in a row, similar to a brand/partners slider? The current preview output is not displaying as desired. Here is the code I have: <div class="image-gallery"> <div class ...

The z-index issue with Bootstrap modal is not being resolved on Firefox and Internet Explorer

I am encountering an issue with my bootstrap modal that includes a jquery datepicker. Specifically, the datepicker is styled as follows: .datepicker{ z-index:1000;} Interestingly, it functions perfectly on Google Chrome, displaying like this: However, ...

Finding the automatically generated ID of a new document in a subcollection in Firebase Firestore Web V9, using Javascript/React

When a user clicks, I generate a new document in a subcollection associated with that user's profile. Below is the function responsible for this: // Function to create a new checkout session document in the subcollection under the user's profile ...

What is the reason that custom styling for a single react component instance does not function properly?

In my current view, I have integrated a react component as shown below: <Jumbotron> Lots of vital information </Jumbotron> I am looking to give this particular instance a unique style, like using a different background image. However, addin ...

Having trouble setting up npm package (fsevents) on Mac OS Catalina?

I'm facing an error when trying to run the npm install express --save command. Can someone assist me in resolving this issue? The error message is as follows: > email@example.com install /Users/delowar/Desktop/ytdl/node_modules/chokidar/node_modu ...

Include a class above the specified element; for instance, apply the class "act" to the "<ul>" element preceding the "li.item1"

Hello there! I need some assistance, kinda like the example here Add class and insert before div. However, what I really want to do is add the class "act" to a class above that matches the one below: Here's how it currently looks: <ul> ...

PHP not receiving values when making an AJAX POST request

My AJAX file below is where I pass all the values from my text boxes and post them to edu.php. In edu.php, I intend to update two tables - details and test. However, nothing seems to be updating in my database. When I checked the values with var_dump, the ...

Update the background image URL by setting it as the value of an input field

There are three elements in play here: an input field, a span element, and a div with a background image property. <span>Go</span><input id="ImageUrl"/> <div id="Image"></div> I am working on a script where when a user ente ...

Stop const expressions from being widened by type annotation

Is there a way to maintain a constant literal expression (with const assertion) while still enforcing type checking against a specific type to prevent missing or excess properties? In simpler terms, how can the type annotation be prevented from overriding ...

MongoDB does not treat aggregate match pipeline as equal to in comparisons

I've been tackling an aggregate pipeline task for MongoDB where I need to retrieve items that do not have a specific user ID. Despite my efforts, I'm struggling to get it right. I attempted using $not, $ne, and $nin in various ways but couldn&ap ...

Using Ajax with Controller Action in Yii2

As a newcomer to programming, I am facing an issue where I need to call a function when the user inputs data and clicks the submit button. Although I am working with Yii2, I lack experience in Ajax. Despite my efforts, the controller action is not being tr ...

Guidance on marking a menu item as selected when choosing its sub-item

I've been tasked with creating a menu and I want to ensure that the menu item stays selected when its subchild is selected. Below is a snippet from my CSS file: #wrapper { width:100%; height:500px; } h2 { color:#787878; } // more ...

What is the best way to incorporate multiple versions of jQuery on one webpage?

Is it possible to use multiple versions of jQuery on a single page? I need two different versions for various functions, but they seem to be conflicting with each other. If I implement jQuery noconflict, will the product scripts still work? <script typ ...

Issue with jQuery hide() function in Internet Explorer 9

I need help with creating a hidden div that becomes visible when a user clicks a link. The code I have works in FF / IE7 / IE8 but not in IE9, where the div is always visible without any content. Any advice is appreciated! <script> $(document).r ...

Retrieving external JSON data with JavaScript

I am attempting to utilize a specific service for proxy checking. They offer an uncomplicated API that delivers JSON data. My goal is to retrieve this JSON on my own server. Despite various attempts, I consistently encounter either a CORS request issue or ...

How can I choose records from collection 'x' in mongodb?

I need to fetch all fields from my database using an API call Here is my code: exports.objfields = async (req, res, next) => { try { var db = mongo.connection; var objeto = req.headers.objeto; const result = db.db.collection(objeto).find( ...

How can we eliminate duplicate arrays of objects within a multi-dimensional array using ReactJS and JavaScript?

let galleryItems = [ {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', size: 91153, …}, {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', si ...

Can you explain the process of implementing a conditional render with three parts in React?

Currently, I am attempting to implement a conditional render but encountering some issues. Is it achievable? location: `${props.off_campus_location ? ( `${props.off_campus_location}` ) : ( `${props.campus_location.name}` ) : ( `${props.location_type}` )}` ...

How can I implement the `withAuth` design using `iron-session` in Next.js?

I really appreciate the design pattern used in next-auth → https://next-auth.js.org/getting-started/client#custom-client-session-handling The main concept is to set .auth = true and then verify it in _app.tsx like this: export default function App({ C ...

Differences between Creating and Updating Objects in JavaScript

When working with JavaScript, it is important to consider the best practices for performance optimization. Take a look at these two examples: Example 1: var x = {}; x.a = 10; Example 2: var x = {}; x = {a: 10}; Are there any noticeable differences in ...