Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
how to adjust a div width to expand and shrink back on scroll

I was doing this and thought its easy until I got stuck.
I want to expand a div with on scroll down to 100% until the bottom of the div then at the bottom shrink back to 90% and on scroll top doing reverse
I have tried using: parallax library which wasn't helpful
here is a live sample: https://stackblitz.com/edit/react-ybdmbn?file=src/components/AdjustContainer.jsx

have tried to use the useEffect hook, like below

const [adjustWidth, setAdjustWidth] = useState()

    useEffect(() => {
        window.addEventListener('scroll', handleScroll);
        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
    }, []);


    const handleScroll = (e) => {
        let scrollTop = window.scrollY
        if (scrollTop !== 0) {
            // console.log('e', e);
            setAdjustWidth(
                {
                    width: '100%',
                    transition: 'width 2s'
                }
            )
        } else {
            setAdjustWidth(
                {
                    width: '90%',
                    transition: 'width 2s'
                }
                )
        }
    }

      <div className={styles.AdjustContainer}  style={adjustWidth}>

           my content
      </div>


about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Looks like instead of just checking if the user has scrolled, you need to check whether the div is in view and change the width accordingly.

import React, { useEffect, useState, useRef } from 'react';
    
const AdjustContainer = ({ children }) => {
  const ele = useRef();
  const [width, setWidth] = useState('90%');

  useEffect(() => {
    const observer = new IntersectionObserver(handleIntersection);

    observer.observe(ele.current);

    return () => {
      observer.unobserve(ele.current);
    };
  }, []);

  const handleIntersection = (entries) => {
    entries.map((entry) => {
      entry.isIntersecting ? setWidth('100%') : setWidth('90%');
    });
  };

  return (
    <div
      ref={ele}
      className="adjustContainer"
      style={{ width, transition: 'width 2s' }}
    >
      {children}
    </div>
  );
};
export default AdjustContainer;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!