Tips for dynamically resizing a div element as a user scrolls, allowing it to expand and contract based on

I was working on a project and everything seemed easy until I hit a roadblock.
What I am trying to achieve is expanding a div to 100% when scrolling down to the bottom of the div, then shrink it back to 90% at the bottom and do the reverse when scrolling up. In other words, the width of the div at the top and bottom should be controlled by the scroll direction.
The project I'm working on is using SSR next.js
I attempted to use the parallax library from this link but it didn't solve my issue.
You can see a live sample here: https://stackblitz.com/edit/react-ybdmbn?file=src/components/AdjustContainer.jsx

I also tried using the useEffect hook as shown below:

const [adjustWidth, setAdjustWidth] = useState()
const adjustRef = useRef();
  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, [adjustRef.current]);

  const handleScroll = () => {
    console.log('scrollTop', adjustRef.current.scrollTop);
    if (adjustRef.current) {
      const { scrollTop, scrollHeight, clientHeight } = adjustRef.current;
      if (scrollTop + clientHeight === scrollHeight) {
        // do something here
        console.log('Reached Bottom');
      }
    }
  };

      <div className={styles.AdjustContainer}  ref={adjustRef}>

            {myContent.map((module, i) => (

                    <MyContent {...module} key={i}  />
                ))}
      </div>


Answer №1

It seems that simply checking if the user has scrolled is not enough; you also need to ensure that the div is visible on the screen in order to adjust its width.

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.intersectionRatio ? setWidth('100%') : setWidth('90%');
    });
  };

  return (
    <div
      ref={ele}
      className="adjustContainer"
      style={{ width, transition: 'width 2s' }}
    >
      {children}
    </div>
  );
};
export default AdjustContainer;

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

Why has my dropdown menu decided to go horizontal, rather than dropping down as it should?

Hi there! I'm new to css and tried following a tutorial with some tweaks. However, when adding a drop down menu using lists, it ended up going sideways instead of downward. Can anyone help me out? I also would like to have a collapsible menu implemen ...

Styling does not seem to apply to inner components in NEXTJS

I am attempting to create a ChatGPT replica using Next.js and Tailwind CSS. My focus is currently on the main chat screen, where each message is displayed using a separate Message component with its own styling. However, I am facing an issue where the styl ...

Issue with concealing floated elements within a container div

I am currently facing an issue with trying to hide floated divs within a parent div, but unfortunately my code is not working as expected. Here is the code snippet: div.scrollarea { overflow: scroll; width: 400px; ...

I am looking for an image search API that supports JSONP so that users can easily search for images on my website

I am currently in the process of creating a blog platform. My goal is to allow users to input keywords on my site and search for images directly within the website. This way, I can easily retrieve the URL of the desired image. ...

Ways to customize easypiechart appearance with CSS styling

I am looking to create a circular counter similar to the one shown below. I have tried using easy-pie-chart but I am unsure how to style the circles to look like the example provided. Is there a way to achieve this through CSS? Any recommended resources o ...

Combining actions in a chain within an NgRx effect for Angular

After successfully working on an effect, I now face the challenge of chaining it with a service called in a subsequent action after updating the state in the initial action through a reducer. Here is the effect code: @Effect() uploadSpecChange$: Observab ...

Measuring Euler Angles with 9-Axis Analog Sensor Data

I am trying to calculate Euler angles using analog sensor data in JavaScript. The sensor data consists of gyro, accelerometer, and magnetometer readings in three dimensions. I find the mathematical aspect a bit challenging, so any assistance or advice woul ...

Unable to retrieve the child value using getJSON

I am currently retrieving data from an API that provides information in a specific format. Here is an example of the JSON data I receive: { "total":1, "launches":[ { "name":"Falcon 9 Full Thrust | BulgariaSat-1", "net":"June 23, 2017 1 ...

Is it possible to align text to an image within an input text field?

<input type="text" class="usernm" style="color:black;font-weight: bold;outline-width: 0;" id="username" /> I have a question about styling HTML. I am attempting to include an icon inside a text field, but I'm strugglin ...

"Ensuring Your SVG Icon is Perfectly Centered: A Step

My SVG icon is currently aligned to the left, but I want to center it. I tried using the following code, but it doesn't seem to be working: .parent{ display: flex; align-items: center; font-size: 13px; } span{ margin-right:10px } When I look at the S ...

SSR alerts pop up when attempting to load specific sections of the primary app interface that are dependent on the ongoing session

I have created an administrative dashboard using Next.Js. My goal is to implement the following functionality: When a user logs in through the /login route Show a loading screen while processing the login In the / route, if the user exists, the app will l ...

Execute code after selecting the link

To simplify my question, I will provide an example: Suppose I have two sample pages that I want to demonstrate: Page 01 <script> var demo = 'X1'; alert(demo); $( document ).ready(function() { $("#cont").on("click" ...

Is it possible to reduce a field value in firestore after successfully submitting a form?

I have a variety of items retrieved from firestore: availability : true stocks: 100 item: item1 https://i.stack.imgur.com/hrfDu.png I am interested in reducing the stocks after submitting a form. I used the where() method to check if the selected item m ...

What is the solution for halting code execution in a foreach loop with nested callbacks?

Currently, I am in the process of setting up a nodejs database where I need to retrieve user information if the user exists. The issue I'm facing is that when I return callback(null) or callback(userdata), it does not stop the code execution and resul ...

Accessing the jQuery Ajax success variable

I have a PHP function that returns an array with an element error containing the value 'ERR': var updatePaymentType = function(plan_pt_id, pt_id){ var error = null; var data = new Object() data["function"] = "update"; ...

Tips for utilizing browser cache in AJAX requests to prevent loading the refreshed JSON file

It may seem like a strange question, but I'm experiencing an issue with an AJAX call to a JSON file. Both the request and response headers do not indicate to not use cache, and in the browser settings, the Disable cache option is not checked. What mor ...

Tips for incorporating a PDF file into a website when the Adobe Reader add-on is disabled in Internet Explorer

I attempted to insert a PDF into my website using the <embed> tag. Unfortunately, it doesn't seem to be functioning properly in Internet Explorer when the Adobe Reader add-on is disabled. Is there a solution that will allow it to work even if th ...

Description for script tag in HTML body

How can I embed a GitHub gist on my website using the script tag? I currently use the following code: <script src="https://gist.github.com/uname/id.js"></script> I've been wondering if there is a way to add alt text in case the gist fail ...

Encountering the error message "handleChange is not a function" when trying to select a date in Material UI

Encountering an error message 'handleChange is not a function' when selecting a specific date in the DatePicker component. The DatePicker component is nested within the Controller component of react-hook-form. The expected behavior is to display ...

Error: The value is null and cannot be read

My external application is set up within a const called setupRemote, where it starts with the appConfig in the variable allowAppInstance. export const setupRemote = () => { if (isRemoteAvailable) { try { ... const allowAppInstance = S ...