What is the best way to enlarge an element when scrolling downwards within the element?

I am looking to create a div that dynamically adjusts its height based on the user's scrolling behavior. The goal is for the div to expand to the very top as the user scrolls downward, and stop when it reaches 70% of the container/parent element. Is there a library available to achieve this smoothly without using incremental adjustments to the height property? Please see the example below:

<div id='container'>
Scroll up to here
<div id='panel'>
As the user scrolls down in this div, expand it to the top incrementally.</br></div>
</div>

#container {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: red;
}

#panel {
  position: fixed;
  width: 100%;
  height: 70%;
  bottom: 0;
    background-color: green;
    overflow-y: scroll;
}

https://jsfiddle.net/1ekpx3sd/

Answer №1

Here is my innovative solution that dynamically adjusts the height of a div element as the user scrolls on the page by detecting the scroll event. This script calculates the new height based on the user's scrolling behavior, setting it to 70% plus the distance scrolled but constrained within a certain limit which can be modified to suit your needs:

function adjustHeight() {
    var mainDiv = document.getElementById("main");
    var wrapper = document.getElementById("wrapper");
    
    var scrollableHeight = wrapper.offsetHeight;
    var newY = mainDiv.scrollTop;
    
    // DETERMINE THE MAX HEIGHT BASED ON PERCENTAGE OR FIXED AMOUNT
    maxHeight = scrollableHeight * 0.9;
    
    var newTargetHeight = Math.min(maxHeight, 0.7 * scrollableHeight + newY);
    
    mainDiv.style.height = newTargetHeight + "px";
    
    
    document.getElementById("content").style.marginTop = Math.min(newY, scrollableHeight - maxHeight) + "px";
}

document.getElementById('main').addEventListener("scroll", adjustHeight);
#wrapper {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: red;
}

#main {
  position: fixed;
  width: 100%;
  height: 70%;
  bottom: 0;
  background-color: green;
  overflow-y: scroll;
}

#content {
}
<div id='wrapper'>
Keep scrolling up for more content...
<div id='main'>
<div id='content'>
Responsive dynamic div height according to scroll behavior in action... Insert your lengthy text or content here...
</div>
</div>
</div>

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

Attempting to create a child process within the renderer by triggering it with a button click

I'm currently developing an electron application where I am attempting to initiate a child node process (specifically to run a Discord.JS bot). Below is the code snippet in question: index.html: <tr> <th class="title-bar-cell" ...

Guide: Passing and reading command line arguments in React JavaScript using npm

When launching the react application, I utilize npm start which is defined in package.json as "start": "react-scripts start -o". Within the JavaScript code, I currently have: const backendUrl = 'hardCodedUrl'; My intention ...

The PHP script is not receiving any data when checking if the value is set in the $_POST variable

I'm attempting to transmit values from a JavaScript file using POST method to a PHP page. Here is the AJAX code: let userInput = $input.val(); $.ajax({url: "../checkout/test.php", type : 'post', data : {'userInput': user ...

When working with Next.js Components, be aware that using a return statement in a forbidden context can lead to

Whenever I try to add a new component to my Next.js project, I encounter an error that displays the following: `./components/GridMember.js Error: error: Return statement is not allowed here | 6 | return (test); | ^^^^^^^^^^^^^^^^^^^^^^^^^ Caused ...

What could be causing the modal to not appear when clicking on this div?

$(function() { $("#pagination a").trigger('click'); // When the page loads, trigger a click event $('body').on('click','div.well well-sm',function(){ var list = $(this); $('#myModal .modal-title').h ...

Avoiding jQuery selector

What is the reason for the selector working in the first example but failing in the second one? Check out jsfiddle. <div id="hello[1][2]_world">&nbsp;</div> <textarea id="console"></textarea> <script> $(document).re ...

Displaying an image on a jsp page

In my current JSP, within the HTML section, I have the following: <select> <%if(size == 1)%> <option>None selected</option> <%if(size > 1)%> <option>1</option> </select> Additionally, I have this ima ...

A guide on eliminating null or empty values within a React table's map

Is there a way to determine if the value of {row.storeId} is null or empty? If it is, I would like to display NA within the <TableCell>. {props.tableData.map(row => ( <TableRow key={row.storeId}> <TableCell>{row ...

Creating a dynamic multi-select feature in AngularJS with ng-repeat

I'm relatively new to AngularJS and JavaScript, but I've managed to create a functional multi-select list. The ng-model linked to the dropdown is part of a "user" DTO object, specifically a property that stores an array of "groups" the user can j ...

Encountering issues with returning values correctly when using module.exports in Node.js

function userLogin(username, password) { var status; var userid = username; User.findOne({ 'username': [userid], 'password': [password] }, function(err, user) { if (!user) { console.lo ...

switch out asterisk on innerhtml using javascript

Is there a way to replace the asterisks with a blank ("") in the innerHTML using JavaScript? I've attempted this method: document.getElementById("lab").innerHTML = document.getElementById("lab").innerHTML.replace(/&#42;/g, ''); I also ...

How can I effectively implement a withAuth higher order component (HOC) in TypeScript within Next.js?

Currently, I am working on a Next.js application and implementing the next-auth package. My goal is to develop a Higher Order Component (HOC) that can determine if the component has an active session or not. Along with this, I am utilizing eslint for code ...

What is the correct way to utilize window.scrollY effectively in my code?

Is it possible to have a fixed header that only appears when the user scrolls up, instead of being fixed at the top by default? I've tried using the "fixed" property but it ends up blocking the white stick at the top. Adjusting the z-index doesn&apos ...

Having trouble with JSON search not functioning as expected in Select2 4.0?

After numerous hours of effort, I finally managed to successfully load and display the json file, complete with the flag icons using Select2 4.0. The code ended up appearing deceptively simple. However, I am now facing an issue where the search function i ...

The table printing settings are not compatible with portrait and landscape orientations

I am facing an issue with printing a table on my webpage. When I try to print using Control+P or window.print();, the width of the table does not adjust properly for portrait or landscape orientation. The table ends up exceeding the paper width. How can I ...

Utilizing the map() function to iterate through a list of outcomes and assigning the resulting array as the state of a component in ReactJS

Currently, I am facing an issue with assigning an array value to the state in my react project. In order to do this, I have initialized my state as follows: constructor(props) { super(props); this.state = { category: [] } } My objec ...

Looking to deactivate a particular checkbox in a chosen mode while expanding the tree branches

I encountered an issue with a checkbox tree view where I needed to disable the first two checkboxes in selected mode. While I was able to achieve this using the checked and readonly properties, I found that I could still uncheck the checkboxes, which is no ...

Setting the outcome of an Ajax call as a global variable in JavaScript

I have a method that uses AJAX to request data and returns a JSON string containing Tokens records. I am trying to store this result in a global variable named 'tokens' so I can access it in other functions. After assigning the result to the &ap ...

How to selectively load specific scripts in index.html with the use of angular.js

Let me address a problem I'm facing with a large development project. It seems that the current setup does not function properly on Internet Explorer. My idea is to only load files that are compatible and do not generate errors when accessed through I ...

Interfacing Highcharts with Angular for seamless data binding across series

I am fairly new to using highcharts and I am having difficulty binding my data into the series parameter. In my controller, I have an array of objects that I want to display (when I use console.log, I can see that they are all properly there) this.plotDa ...