skip to Main Content

I’m currently using the data-aos attribute to apply the "fade-up-right" animation to an element in my web page, like this:

<div className="des__Container" data-aos="fade-up-right">

Now, I want to change the animation specifically when the screen width is at its maximum of 768 pixels.

Is it possible to conditionally modify this animation based on the screen width? If not, are there any alternative solutions or best practices for achieving this?

Any guidance would be greatly appreciated. Thanks in advance!

3

Answers


  1. You can achieve this by adding CSS media queries to the animation. You can try the following code:

        /* Default animation for screen widths below 768px */
    .des__Container {
      animation: fade-up-right 1s ease both;
    }
    
    /* Custom animation for screen widths of 768px and above */
    
    @media (min-width: 768px) {
      .custom-animation {
    animation: your-custom-animation 1s ease both;
     }
    }
    
    Login or Signup to reply.
  2. Here’s an approach

    
    const MyComponent = () => {
      const [screenWidth, setScreenWidth] = useState(window.innerWidth);
    
      useEffect(() => {
        const handleResize = () => {
          setScreenWidth(window.innerWidth);
        };
    
        window.addEventListener('resize', handleResize);
    
        return () => {
          window.removeEventListener('resize', handleResize);
        };
      }, []);
    
      return (
        <div
          className="des__Container"
          data-aos={screenWidth <= 768 ? 'your-alternative-animation' : 'fade-up-right'}>
            {/* Content */}
        </div>
      );
    }
    
    Login or Signup to reply.
  3. You can create a custom hook called useWindowSize which gives you width of the window and then inside your div, you can conditionally add/remove data-aos:

    Code for hook:

    import { useState, useEffect } from "react";
    export const useWindowSize = () => {
      const [windowSize, setWindowSize] = useState({
        width: window?.innerWidth,
        height: window?.innerHeight
      });
    
      useEffect(() => {
        // Function to update the window size
        function handleResize() {
          setWindowSize({
            width: window.innerWidth,
            height: window.innerHeight
          });
        }
    
        // Add event listener to listen for window resize
        window.addEventListener("resize", handleResize);
    
        // Clean up the event listener on component unmount
        return () => {
          window.removeEventListener("resize", handleResize);
        };
      }, []); // Empty dependency array ensures the effect runs only on mount and unmount
    
      return windowSize;
    }
    

    Code sandbox:
    https://codesandbox.io/s/fervent-flower-8gln2c?file=/hooks/useWindowSize.js:0-758

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search