The element's height appears to be fluctuating unexpectedly when I attempt to adjust it using percentage values within a narrow range

I'm utilizing React and Bootstrap in this project.

Here's an overview of my code: I have an element with height set to 0, in rem. My goal is to make the height of this element increase as I scroll down the page, creating the illusion that it is appearing out of nowhere.

The handleWorksTitle function essentially takes the element and calculates the height it should have based on the position of its bottom rectangle within the window. Once the bottom rectangle comes into view, the "animation" starts by calculating the height as "by this point you must reach 100% of the target height". The target point is determined by the bottomPivot.current, which is a percentage of the screen height starting from the bottom.

The code encounters issues if the window height is too small or if the value of bottomPivot.current is too low. Essentially, if the distance between the bottom of the screen and the bottom pivot is too short, the code breaks.

This is how the function works:

    function handleWorksTitle() {

        //get the container that we will modify
        const titleCont = document.querySelector("#works-title-cont");

        // get the current position (bottom) of the container
        const currY = titleCont.getBoundingClientRect().bottom;

        // check if the containers bottom is within the screen boundaries
        if(currY <= window.innerHeight) {

            // calculate the target height based on screen breakpoint
            const heightTarget = breakpointStateRef.current == breakpoints.lg ? worksTitleMovLg : (breakpointStateRef.current == breakpoints.md ? worksTitleMovMd : worksTitleMovSm);

            // calculate the desired height (in percentage)
            // bottomPivot.current is 30 in this example
            const percentage = GetPerCurrToTarget_Bottom(currY, bottomPivot.current);

            // convert the percentage to a real value (in css rem units)
            const value = heightTarget / 100 * percentage;

            // apply the height value
            titleCont.style.height = `${value <= heightTarget ? value : heightTarget }rem`;
        }
    };

This function is triggered by the window's "scroll" event:

// added line inside useEffect([])
window.addEventListener("scroll", handleWorksTitle);

Here is the GetPerCurrToTarget_Bottom function:

export function GetPerCurrToTarget_Bottom(currLoc, targetLoc) {

    const rangeVal = window.innerHeight - targetLoc;
    const valInRange = window.innerHeight - currLoc;
    const percentage = (100 / rangeVal) * valInRange;

    return percentage;
}

The code functions correctly on most standard sized screens, but it starts breaking as the screen height decreases without any apparent reason. After reaching a certain height, the element's Y value begins to oscillate between two numbers, causing the element to jump back and forth on the screen.

Here's part of my JSX and some CSS for reference:

<div className="col">
    <div id="works-title-cont">
        <p id="works-title" className={CalculateWorksTitleSize(breakpointState)}>Works</p>
    </div>
</div>
/* styles specific to the Works title text */
#works-title-cont {
    display: flex;
    justify-content: center;
    
    width: 100%;
    height: 0rem; /* manipulated dynamically in code */
    max-height: 100%;

    overflow-y: hidden;
}

Do you have any insights or suggestions?

Thank you!

I expected the code to work consistently regardless of the screen's height or the value of bottomPivot.current (which also causes the code to break when too low).

Answer №1

Problem solved! I realized my mistake in understanding how HTML displays content based on CSS' position property (static, relative, absolute).

Initially, my element was set to static and the workaround I was using ended up affecting the layout of elements below it, causing issues.

Simply changing the parent to relative and the child to absolute, then fine-tuning the position with the transform property did the trick.

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

Implementing a custom body class in AngularJS when utilizing partials

Looking for some help with AngularJS. I have an index.html file, along with controllers and partials. The <body> tag is located in the index.html. I am trying to set the class for the body using my controller. After adding a value to $scope.body_c ...

Leveraging the power of a local environment to conduct sanity checks on

Encountered an error: Uncaught error: Can't find variable: process http://localhost:3333/sanity.config.ts:5:26 The issue lies within the .env.local file. I discovered this when manually inputting my project ID into the sanity config file. Howeve ...

Is it possible to implement cross-domain login with Passport.js?

Is it possible for a user to log in from a different domain? For example, the main site has a login form that uses AJAX to post to a route on my Node.js server. // Submit form to Node server FROM WEBSITE $('#submit-project-form').submit(function ...

Creating an object property conditionally in a single line: A quick guide

Is there a more efficient way to conditionally create a property on an object without having to repeat the process for every different property? I want to ensure that the property does not exist at all if it has no value, rather than just being null. Thi ...

Understanding the usage of jQuery transitionend to prevent interruptions in CSS animations

I found a similar thread on StackOverflow but I'm struggling to apply it in my current scenario. The Setup (Welcome Ideas) I've developed a jQuery slider that will have multiple instances on one page, each containing an unknown number of childr ...

Having trouble initiating a cloned React application

After cloning a react app from Github to my local computer, I encountered an issue when trying to run 'npm start' which resulted in the following error message: ➜ sweet-movie-app git:(master) npm start internal/modules/cjs/loader.js:596 ...

Displaying Spinner and Component Simultaneously in React when State Changes with useEffect

Incorporating conditional rendering to display the spinner during the initial API call is crucial. Additionally, when the date changes in the dependency array of the useEffect, it triggers another API call. Question: If the data retrieval process is inco ...

Exploring nested objects in Javascript through iterating and extracting all properties in a continuous loop (Updated)

In my code, I created an object with two sub-objects structured like this: var testObject = { "page":{ "type": "ePurchase", "title":"Purchase confirmation" }, "user": { "name": ...

The webpage is unreachable on localhost after attempting to write to a file using node.js

I'm currently attempting to update a file using Node.js. I have a form that contains checkboxes, and upon form submission, the server should update the file based on which checkboxes are selected: a, b, or c. The JSON file structure is as follows: { ...

Choose various selections from a drop-down menu using AngularJs

I am currently working on a project where I need to be able to select multiple options from a dropdown menu. The code snippet for this functionality looks like the following: //Controller $scope.data = [{id: 1, Country: Zambia}, {id: 2, Coun ...

Convert angular-tree-component JSON into a suitable format and dynamically generate checkboxes or radio buttons

Currently, I am using the angular-tree-component for my treeview implementation. You can find more details about it in this reference link. The array structure I am working with is as follows: nodes = [ { id: 1, name: 'root1', ...

Struggling to align text to the far left within a text area using Bootstrap

When I accidentally place my cursor earlier in the text area, it starts writing from that point, leaving some unwanted spaces at the beginning. I prefer it to start from the extreme left, similar to how it behaves in input boxes. Below is the code snippet ...

What is the best way to extract a JSON object from a website search using getJSON or similar techniques?

Can anyone provide guidance on utilizing .getJSON() to access JSON-encoded information from a website that is being searched? I've implemented a Google Custom Search API for my site with the aim of retrieving the JSON file from the search results. Fo ...

The installation of the Electron application on the system is failing to launch due to an issue with the "iohook" library utilized in the "main.ts" file

I am currently developing an application with ElectronJS and encountering a problem. Just to give some context, I am utilizing the electron-react-boilerplate for my project. Additionally, I am incorporating a npm package called iohook to capture system inp ...

Use a dropdown menu to update the selected value

Issue with displaying drop down values in the second list, despite trying various solutions. When a user selects a country, the corresponding state should be populated from the database into the second drop-down. Any assistance would be greatly appreciated ...

Informing a screen reader in Vue.js through the use of aria-live features

My goal is to make a vue component that dynamically announces information to a screen reader when certain events occur on my website. I have managed to achieve this functionality by having a button populate a span with text containing the attributes aria- ...

Utilizing Node.js with Redis for organizing data efficiently

Currently, I am in the process of configuring a Redis cache system for storing incoming JSON data in a specific format. My goal is to create an ordered list structure to accommodate the large volume of data that will be stored before eventual deletion. Th ...

Guide to reference points, current one is constantly nonexistent

As I work on hosting multiple dynamic pages, each with its own function to call at a specific time, I encounter an issue where the current ref is always null. This poses a challenge when trying to access the reference for each page. export default class Qu ...

The React front-end struggles to display MongoDB entries and eventually times out after 10 seconds

I am experiencing an issue where my React front-end is unable to fetch details from a MongoDB database and I need assistance debugging the problem. The back-end utilizes a serverless function. Each time I reload the page, my React code fails to locate the ...

Learn how to retrieve JSON data from the Yahoo Finance REST API using Angular 2

Currently, I am in the process of developing an application that needs to fetch data from the Yahoo Finance REST API. To retrieve a table for the symbol "GOOG," I have implemented the following code: export class ActService{ act = []; url = 'http ...