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

Switch between input and the input is not displayed inline

I've been struggling to align the Toggle button with the input box for quite some time now. I really need them to be inline so that they form a grid properly as everything is dynamic. I have experimented with using a Div on its own instead of a label ...

Reset data in React Redux

Recently diving into the world of React and Redux, I've encountered a couple of issues that have me scratching my head. In exploring examples online, I noticed that some login and registration forms stored user input in component state rather than u ...

Implementing a modal component into a React JS page upon loading

I've been working on a webpage using React JS. The site's structure follows MainContent.js --> Main.js --> ReactDOM render. I recently tried to implement a modal popup that worked perfectly in its own project, but ran into issues when impor ...

using recursion within callback functions

In my JavaScript function with a callback, I am utilizing the "listTables" method of DynamoDB. This method returns only 100 table names initially. If there are more tables, it provides another field called "LastEvaluatedTableName", which can be used in a n ...

The proper functioning of border-collapse and empty-cells together is not achieved

Refer to the link provided: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Tables To conceal empty cells, use the rule empty-cells: hide;. This allows a cell's parent element background to shine through the cell if it is emp ...

When accessing req.param on the server side in a Node.js application, it returns undefined

I am currently utilizing nodejs and angularjs for my project. In the client-side javascript file, I made a GET request to the nodejs server with necessary data in parameters. itinerary.js $http({ method : "GET", url : '/createItinerary&apo ...

What is the correct way to incorporate scrollIntoView() using jQuery?

I'm trying to implement a jQuery function that will enable the last reply to scroll into view. This is my current code: function displayLastReply(replies){ replies.each(function() { if($(this).index() < nIniRep || afterReply){ $( ...

Should I consider implementing Flexbox even if I need to cater to users still using IE9?

Currently, I am embarking on a fresh project centered around constructing a chat window. Typically, I would readily employ Flexbox for this endeavor; nevertheless, one of the stipulations for this project is to ensure compatibility with IE9. While I under ...

Is it possible for a Vue data property to have a value that is determined by another Vue data property object?

Within my HTML form, I have implemented the flatPickr (calendar picker) component which generates an input field. I am currently exploring how to dynamically change the class of the input field if the error class function returns true. Below is the flatPi ...

Is it possible to relocate a function that relies on the success callback of Ajax outside of the callback?

According to JSHint.com: Avoid placing function declarations inside blocks. Opt for a function expression or move the statement to the outer function's top. JSHint advises against keeping this function within the success callback. function matchC ...

Removing the day name from an input date in React without relying on Moment.js

I have successfully implemented code to validate dates, but I am unsure how to retrieve the name of the day for a given date input in the field. For instance: if the date input is 12/01/1994, it should display "Wednesday". function isValidDate(inputDate) ...

In this JavaScript tool for counting characters, every carriage return is counted as two characters

Hello there! I have created a character counter in JavaScript that looks like this: <textarea class="SmsText" id="txttemplate" maxlength="160" /> <span id="charsCount">160</span></strong><span>character(s) left</span> ...

Issue with Karma and angular-mocks: The error message "TypeError: 'undefined' is not an object (evaluating 'angular.mock = {}')" is being shown

I am facing an issue while writing unit tests using Karma + Jasmine. The problem arises with angular-mocks when I run grunt test, resulting in the following error message: PhantomJS 1.9.8 (Mac OS X) ERROR TypeError: 'undefined' is not an ob ...

Contact form script malfunctioning, showing a blank white page

Encountering a white screen when trying to submit my contact form with fields for Name, Email, Subject, and Message. I am looking to receive emails through my website. I have double-checked all variable names and everything seems to be correct. Since I am ...

What is causing the check box in the simple_form view to consistently return a value of 1 when checked or unchecked in rails 3.2?

A checkbox with the name "need_delivery" is used to determine whether the next two text boxes should be displayed. These two text boxes are enclosed within a div with the id of task_request_delivery. Below is the code snippet in the simple_form view named ...

The polygon array feature is not functioning as expected in the Google Maps API

I'm currently facing an issue with a code that is supposed to draw polygons from an array in the Google Maps API, but unfortunately, it doesn't seem to be working as expected. <!DOCTYPE html> <html> <head> <script src ...

Is it advisable for me to utilize forceUpdate() or should I explore alternative methods of rendering a React component again?

I am working with a component and trying to rerender it after an API call. The issue I am facing is that even though the winks-count updates after the getWinks API call, it does not reflect on the view unless I refresh the page. I'm not sure if using ...

Tips for retrieving a variable from a $.getJSON function

My question is similar to this one: How can I return a variable from a $.getJSON function I have come across several duplicates on Stack Overflow, but none of them provided a satisfactory answer. I understand that $.getJSON runs asynchronously, and I hav ...

Issue with undefined object in ExpressJS PUT method

Attempting to utilize the PUT method for updating a record in my database, I encountered an issue with the object not being defined. ReferenceError: blogpost is not defined Following this tutorial for routing steps, I noticed that while the variable is d ...

Issue encountered when displaying an organized list in next.js

I have been working on rendering an array of items in descending order based on their values. Everything seems to be functioning correctly, but I keep encountering an error that reads Error: Text content does not match server-rendered HTML. whenever I tr ...