Ensure that when adjusting the height of a div, the content is always pushed down without affecting the overall layout of the page

My webpage contains a div element positioned in the middle of the content, with its height being adjustable through JavaScript code.

I am seeking a way to manage the scrolling behavior when the height of the div changes. Specifically, I want the content to always be pushed downwards and never upwards.

Currently, the content moves either up or down based on the scroll position when the button is triggered.

Below is a basic example:

function toggle(ev) {
    const div = document.querySelector("div");
    if (div.style.height === "336px") {
      div.style.height = "147px";
    } else {
        div.style.height = "336px";
    }
}
body {max-width: 60em; margin: auto;}
<p style="background-color: coral; height: 400px;"></p>
<div style="background-color:grey; height: 147px;"></div>
<button href="#" onclick="toggle()">toggle div size</button>
<p style="background-color: olive; height: 3000px;"></p>

To clarify, I am looking for a solution where the top paragraph remains fixed in its position when the div expands, regardless of the current button location on the window. This means that the bottom paragraph should adjust its position accordingly as well.

Answer №1

To prevent the button from causing the page to scroll when clicked, blur the element using e.target.blur() in the click handler before updating the content height. This way, the window will no longer consider the button as active and won't automatically keep it in view.

const handleClick = e => {
    e.target.blur()
    updateScrollHeight()
}

function adjustSize(ev) {
    const container = document.querySelector("div");
    ev.target.blur();
    if (container.style.height === "336px") {
      container.style.height = "147px";
    } else {
        container.style.height = "336px";
    }
}

document.querySelector("button").addEventListener("click", adjustSize);
body {max-width: 60em; margin: auto;}
<p style="background-color: coral; height: 400px;"></p>
<div style="background-color:grey; height: 147px;"></div>
<button href="#">toggle div size</button>
<p style="background-color: olive; height: 3000px;"></p>

Answer №2

It seems like you are trying to automatically scroll to the bottom when adjusting the height.

function adjustHeight(ev) {
  const targetDiv = document.querySelector("div");
  if (targetDiv.style.height === "336px") {
    targetDiv.style.height = "147px";
  } else {
      targetDiv.style.height = "336px";
  }
  targetDiv.scrollTop = targetDiv.scrollHeight
}

Answer №3

If you want to navigate to a specific element, you can achieve this by using the window.scrollTo function.

<!doctype html>

<style>
    body {max-width: 60em; margin: auto;}
</style>

<script>
function switchSize(event) {
    const targetDiv = document.querySelector("div");
    if (targetDiv.style.height === "336px") {
      targetDiv.style.height = "147px";
    } else {
        targetDiv.style.height = "336px";
    }
    window.scrollTo(0, targetDiv.scrollHeight);
}
</script>

<p style="background-color: coral; height: 400px;"></p>
<div style="background-color:grey; height: 147px;"></div>
<button href="#" onclick="switchSize()">Adjust div size</button>
<p style="background-color: olive; height: 3000px;"></p>

Answer №4

When a button is clicked, the page ensures that the active element stays in view. This may cause the extra height to appear as though it is moving up or down depending on the button's position relative to the screen.

To make it seem like the page did not scroll up after the element expanded, we can simply scroll the page back to its original position before the expansion occurred. This creates the illusion of the height expanding downwards.

1. Store the current page's top position

var pagePosBeforeExpand = window.pageYOffset;

2. Scroll the page back to its original position if the div has been expanded:

// If we are increasing the height, scroll to the previous top...
window.scrollTo({ top: pagePosBeforeExpand });

It's important to note that this approach does not impact collapsing the height again. However, you can modify it accordingly for such scenarios - for instance, by executing the scroll code outside of the 'if' statement.

Illustrative Example:

function toggle(ev) {
    // 1. Save the current position of the top of the page
    var pagePosBeforeExpand = window.pageYOffset;

    const div = document.querySelector("div");
    if (div.style.height === "336px") {
      div.style.height = "147px";
    } else {
        div.style.height = "336px";
        // 2. Scroll the page back to the position it was before we changed the height
        window.scrollTo({ top: pagePosBeforeExpand })
    }
}
body {max-width: 60em; margin: auto;}
<p style="background-color: coral; height: 400px;"></p>
<div style="background-color:grey; height: 147px;">Top of content</div>
<button href="#" onclick="toggle()">toggle div size</button>
<p style="background-color: olive; height: 3000px;"></p>

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

Does the Parent Tag style override the child tag style when hovering?

I am currently dealing with some style issues. How can I apply the styling of the parent tag to the child tag when hovering over it? Let's illustrate this with a simple example. .outer:hover { background: yellow; z-index: 1; position: relativ ...

"Uncovering the dangers of XMLHttpRequest: How automatic web-page refresh can lead

Hello, I have been developing a web interface for some hardware that utilizes an 8-bit microcontroller. The webpage includes HTML, JavaScript, JSON, and XHR (XMLHttpRequest) for communication purposes. My goal is to create a page that updates every 250 ...

Aligning a set of list items horizontally within an unordered list is a great way to maintain a clean

I'm struggling with centering the alignment of li elements within a ul. Below is the excerpt from my code: ul.nav { width: 1000px; margin: 0 auto; list-style-type: none; } .nav li { float: left; width: 300px; } #government { clear: left ...

Issues with data retrieval from PHP file in AJAX submission

During my attempts to utilize AJAX for submitting data to a PHP file, I encountered an issue where the submission was successful and I could receive a message echoed back from the PHP file. However, when trying to echo back the submitted data or confirm if ...

Creating a scrollable table with CSS: A step-by-step guide

My table has too many columns causing it to exceed the width of the screen. I would like to make it scrollable horizontally for a neater and more organized appearance. I believe CSS with the overflow hidden property can achieve this, but I am unsure where ...

JavaScript Object-Oriented Programming - Accessor method that retrieves a property from the parent

Having trouble with implementing getters and setters for model objects in Angular. Facing an error: TypeError: Cannot read property 'firstName' of undefined at User.firstName (http://run.plnkr.co/AvdF2lngjKB76oUe/app.js:35:32) The code snippet: ...

Swapping stylesheets using a hyperlink - a simple guide

Currently, I am creating a website that utilizes PHP, XHTML strict, and jQuery. The main goal is to ensure the site is adaptable for mobile and desktop devices by implementing the principles of Responsive Web Design. This involves serving different stylesh ...

Updating text color in JavaFX for a textarea

I'm having trouble getting this to work. After checking the CSS analyzer in the scene builder, it seems that changing the text color in a textarea requires something like this: .text-area .text { -fx-fill: #1e88e5; -fx-font-size: 32px; } How ...

React: Issue with function not recognizing changes in global variable

When the run button is clicked, it triggers an event. However, clicking on the skip button does not take me to Switch Case 2 as expected. Even though the skip state updates, the function still outputs the old value of skip. const CustomComponent = () => ...

Is it possible to dynamically change the background image using ReactJS?

I attempted to dynamically change the background image style for the div below: Below is my code snippet for implementation: render: function() { var divImage = { backgroundImage : "url(" + this.state.song.imgSrc + "),url(" + this.state.nextImgSrc ...

What is the best method for integrating UL / LI into JSON to HTML conversion?

Currently, I am working on converting a JSON string into HTML format. If you want to take a look at the code, here is the jsfiddle link: http://jsfiddle.net/2VwKb/4/ The specific modifications I need to make involve adding a li element around the model da ...

Utilizing inline javascript to dynamically update the selected option of a radio button

A form on my website includes two radio buttons: one labeled 'trigger_unit' and the other labeled 'normal_unit'. In addition, there is a select drop-down menu with four values and a default NULL option. <select rel="dropdown" name=" ...

User disappears from Firebase after refreshing the page

I've encountered an issue with my Firebase login process. After a page refresh, the user authentication is lost. Even though the user data is stored in LocalStorage, it gets deleted upon refresh. const loginform = document.querySelector('.loginfo ...

"Integrating Laravel 5.4 Backend with Angular 5 Frontend: A Step-by-Step

Currently, I am immersed in a project that involves creating a frontend using Angular 5 and backend business logic using Laravel 5.4 with MySQL Database. As someone new to this technology stack, I find myself grappling with establishing the data flow conne ...

Populate HTML form with return values using jQuery AJAX

I am struggling with retrieving values from jQuery/AJAX and displaying them in an HTML form within the index.php file. This is what my index.php looks like: <script type="text/javascript"> $(document).ready(function () { $('#display'). ...

Utilize INTERFACE-driven capabilities in ReactJS to dynamically render components based on a variable

How can interface-based functionality be used to render components based on tab selection? If we have 3 components as follows: OneTimeOnlyScheduleComponent DailyScheduleComponent WeeklyScheduleComponent We aim to have all of these components implement t ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...

Accessing content from a text file and showcasing a designated line

Apologies if my wording was unclear... In this scenario, we will refer to the text file as example.txt. The value in question will be labeled as "Apple" My goal is to retrieve example.txt, search for Apple within it, and display the entire line where thi ...

It is not possible for ReactJS to disable a button that has been created dynamically

Incorporating ReactJS, I dynamically generate a form using customized JSON data. render() { return ( <div> <ShowForm src={this.state.data} /> </div> ); } After updating with componentDidUp ...

What is the process of using TypeScript to import a constant exported in JavaScript?

In the environment I'm using typescript 2.6.1. Within react-table's index.js file, there is a declaration that looks like this: import defaultProps from './defaultProps' import propTypes from './propTypes' export const React ...