Adjust the height of the parent (div) to match the size of its child (p) following a window resize

$(window).on("resize", function () {

    var totalHeight = 0

    var $p = $("#cwt-help").children();

    $p.each(function () {
        totalHeight += $("#cwt-help").outerHeight();
    });

    $("#cwt-help").css({ "height": totalHeight })
});

I'm attempting to dynamically adjust the height of a parent div to match the height of its child element upon window resize. The issue I'm encountering with this code is that it retrieves the height before the resize event occurs. How can I accurately get the resulting height after resizing? Thanks!

Answer №1

When the resize event triggers, the code gets executed...
And the desired outcome is for it to run after the event has occurred.

What do you think about using a setTimeout() function?

Maybe waiting 100 milliseconds after the event would be sufficient.

$(window).on("resize", function () {

  setTimeout(function(){
    var totalHeight = 0

    var $p = $("#cwt-help").children();

    $p.each(function () {
        totalHeight += $("#cwt-help").outerHeight();
    });

    $("#cwt-help").css({ "height": totalHeight });
  },100);
});

Answer №2

I found a simple solution that works really well. By setting the height of the element to its scrollHeight when resizing the window, everything falls into place effortlessly.

$(window).on("resize", function () {
    $("#cwt-help").css({ "height": $('#cwt-help').srollHeight });
});
#cwt-help{
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="cwt-help">
  <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate.</p>
  
  <p>Velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</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

Is there a way to align all the content in a Bootstrap card to the center?

Need help centering content in a bootstrap card for my semester project. Can't seem to get it right! If anyone can assist, I would really appreciate it. Also hoping to increase the height of the card if possible. <link rel="stylesheet" href= ...

The height of the ReactPlayer dynamically adjusts to accommodate content beyond the boundaries of the page

I have a video on my webpage that I want to take up the entire screen, but currently, users have to scroll a bit to reach the bottom, which is not ideal. This is my JavaScript: <div id="page"> <div id="video-container"> ...

Is it necessary to verify JSON for duplicate keys before loading?

Currently, I am working on loading a text file that contains JSON formatted data. Before parsing the data, I need to validate it. Right now, I am using the following method to load the file: $.getJSON('dataFile', function(data) { } While this ...

Removing white spaces from response HTML in JBoss 5.1 version

Does anyone know of a JBoss 5.1 plugin or utility that can automatically strip leading and trailing white spaces from HTML being sent as a response? Similarly, is there a way to do this for JSP files upon deployment? Any application-specific settings would ...

"Experience the stunning transformation of 3D objects from poor rendering to exceptional quality in the GLTF-Files Online

I am looking to showcase a model created in Blender on a webpage. The issue is that the rendered quality of the model seems poor, especially with the edges not being properly displayed. Interestingly, when viewing the model in an online viewer, the edges a ...

Tips for aligning my divs at the center with bootstrap

Trying to align my divs using bootstrap HTML code: <div id="wrapper" class="container-fluid row"> <div id="left" class="col-lg-4 col-md-4 col-sm-4 col-xs-4"> //content </div> <div id="right" class= ...

How can I eliminate the empty spaces around a bar chart in Kendo UI?

Struggling to eliminate the extra space surrounding the Kendo UI chart below. Could this be due to a gap or spacing issue? The goal is to create a single-line bar chart with only grey appearing on the right side. Access JSFiddle Codes Here $(doc ...

Proto-Type Namespace

I have a class named "Animals" which serves as a namespace for other classes, "Crocodile" and "Monkey": var Monkey = function(Animals) { this.Animals = Animals; }; Monkey.prototype.feedMe = function() { this.Animals.feed(); }; var Crocodile = functi ...

What is the best way to add a style to the currently active link on a NavLink component using the mui styled() function

I have a custom NavLink component that I want to style with an ".active" class when it is active. However, I am not sure how to achieve this using the "styled()" function in MUI. Does anyone know how to accomplish this? Below is the code for my custom Nav ...

The Vuex commit has exceeded the maximum calstack size limit

Currently facing an issue https://i.sstatic.net/l1WWH.png The error seems to be isolated to this specific section mounted() { this.$nextTick(() => { let ctx = this.$refs.canvas.getContext('2d') let { chartType, dataOptions ...

What is the best way to restore the original form of a string after using string.replaceAll in javascript

To ensure accurate spelling check in JavaScript, I need to implement text normalization to remove extra whitespaces before checking for typos. However, it is crucial to keep the original text intact and adjust typo indexes accordingly after normalization. ...

What are the best practices for using .toString() safely?

Is it necessary for the value to return toString() in order to call value.toString()? How can you determine when you are able to call value.toString()? <script> var customList = function(val, lst) { return { value: val, tail: lst, t ...

Equalize the color of overlapping background events with non-overlapping background events in fullcalendar

events:[ {overlap:false, display:'background', start:'2021-12-23 10:15:00', end:'2021-12-23 10:30:00'}, {overlap:false, display:'background', start:'2021-12-23 10:30:00', end:'2021-12-23 10:45:00&a ...

We were caught off guard by the TypeScript error: an unexpected token showed up when we were expecting a constructor,

Trying to implement a function within a class in TypeScript. class Test { function add(x: number, y: number): number { return x + y; } } Encountering an error message stating: TypeScript Unexpected token, A constructor, method, access ...

PHP not able to retrieve JavaScript variable using Ajax

Resolved: I recently discovered that ajax only sends data in that particular moment, and redirecting creates a new instance. I spent hours searching through various Stack Overflow results for solutions, but none of them seem to work. My current challenge ...

Can someone show me how to use the IN operator in a PostgreSQL query in an Express.js (Node.js

My Approach to Writing Code var employees=[1,2,3]; await client.query( "SELECT user_id FROM group_user WHERE user_id IN($1)", employees ); An error is thrown indicating that only one parameter needs to be provided ...

How can I unselect a radio button by double clicking on it?

I am in need of a specific feature: When a user clicks on a radio button that is already checked, I want it to become unchecked. I've attempted to implement this code but unfortunately, it has not been successful. $(document).on('mouseup' ...

Injecting Custom HTML Tag through JavaScript on Page Load in Google Tag Manager

When attempting to inject events into the data layer upon loading DOM pages on my website, I encountered an issue. Since I lack access to the website code and developers are reluctant to make additions, I decided to implement this through a custom HTML tag ...

Customizing Material-UI styles with type overrides

Is there a way to change the MuiIconButton-root class when using MuiSvgIcon with the fontSizeSmall attribute? import React from 'react' import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles'; const theme = createMuiT ...

Ways to Update/Overwrite Current Information in HTML Using Vue

I have experience creating templates for Vue components using JavaScript. Imagine I have HTML that is generated on the server side with a language called UTL: <table> <tr> <td>[% example_var; %]</td> <t ...