skip to Main Content

I want to create an animation that is responsive to the users display height. I created a variable that stores the height of the document in javaScript but I dont know how to create a keyframe animation in javaScript that will allow be to use that variable.

For example, if I wanted this keyframe animation to be created in javaScript, how would I do it.

@keyframes fadeIn {
    from{
        opacity:0%;
        
    }

    to{
        opacity:100%;
        
    }
    
}

2

Answers


  1. You can go for any js animation library. I would recommend GSAP (GreenSock Animation Platform) or anime.js.

    For example, in GSAP you can accomplish such things:

    var element = document.querySelector('.myElement');
    
    gsap.to(element, {
      duration: 2,
      keyframes: [
        { opacity: 0, scale: 0 },
        { opacity: 1, scale: 1.2 },
        { opacity: 1, scale: 1 }
      ],
      repeat: -1 // Repeat indefinitely
    });
    

    Also check out anime.js .They provide a variety of advance css animation properties.

    Login or Signup to reply.
  2. You also can resolve this problem from the other perspective.
    You can use CSS Variable inside your keyframes like this

    @keyframes maxHeightAnimated{
        from{
            max-height: 0;
        }
        to{
            max-height: var(--document-height)
        }
    }
    

    And then you can just set the value of the CSS variable dynamically at any point that you want via your JS:

    document.addEventListener("DOMContentLoaded", () => {
        let r = document.querySelector(':root')
        r.style.setProperty('--document-height',document.body.offsetHeight + 'px')
        $(window).on('resize', () => {
            let r = document.querySelector(':root')
            r.style.setProperty('--document-height',document.body.offsetHeight + 'px')
        });
    }
    

    In the example, I am setting this value on document loaded and window resize events. What guarantees me that –document-height always contains actual height

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