Search code examples
javascripthtmlcssgsapscrolltrigger

Stop overflow of an element while ScrollTrigger


I'm doing scaling on scroll trigger, the '.square' class when ScrollTriggered zooms in and overflows outside of the '.test' class, I want the scaling to be visible inside of the '.test' class and don't want it to overflow on other containers, what's wrong with my code?

gsap.registerPlugin(ScrollTrigger);

const tl = gsap.timeline({
    scrollTrigger: { 
        trigger: ".square", 
        start: "top top",
        end: "+=100%",
        scrub: true,
        pin: true,
        markers: true, 
    }
})

.to(".square", {
    scale: 2, 
    ease: "none"
})
    html, * {
        padding: 0px;
        margin: 0px;
    }

    body {
        display: flex;
        justify-content: center;
    }

    .container {
        width: 50%;
    }

    .test {
        width: 100%;
        height: 500vh;
        background-color: black;
    }

    .square {
        width: 100%;
        height: 100px;
        background-color: yellow;
    }
<body>
    <section class="container">
        <div class="test">
            <div class="square"></div>
        </div>
    </section>
    <section></section>
</body>


<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/ScrollTrigger.min.js"></script>


Solution

  • Add a clipping path to the .test class:

    gsap.registerPlugin(ScrollTrigger);
    
    const tl = gsap.timeline({
        scrollTrigger: { 
            trigger: ".square", 
            start: "top top",
            end: "+=100%",
            scrub: true,
            pin: true,
            markers: true, 
        }
    })
    
    .to(".square", {
        scale: 2, 
        ease: "none"
    })
        html, * {
            padding: 0px;
            margin: 0px;
        }
    
        body {
            display: flex;
            justify-content: center;
        }
    
        .container {
            width: 50%;
        }
    
        .test {
            width: 100%;
            height: 500vh;
            background-color: black;
            overflow: hidden;
            clip-path: inset(0 0 0 0);
        }
    
        .square {
            width: 100%;
            height: 100px;
            background-color: yellow;
        }
    <body>
        <section class="container">
            <div class="test">
                <div class="square"></div>
            </div>
        </section>
        <section></section>
    </body>
    
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/gsap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/ScrollTrigger.min.js"></script>