Skip to content
Advertisement

Change div height back to dynamic

I have the code below to change the height of a div to equal that of its parent.

$('#infodiv').css("height",$("#infocol").outerHeight());

The problem is that the height of the child element #infocol, is no longer dynamic if i load new content inside of it. Is there a way to make the child element dynamic again after i have set the height with the above code?

I have tried to reconfigure its height after the content is loaded with the same code, but so far that hasn’t worked.

Advertisement

Answer

There is a way you can solve this issue using ResizeObserver

However, note that it’s not supported in some browsers, check the page I’ve linked for further details. Here is a working example:

$(function () {
   $("#add-content").click(function () {
      $(".first-col").append("<p>More dynamic content...</p>");
   });
   
   // keep the second-col same size as first
   $(".second-col").css('height', $(".first-col").outerHeight());
   
   const resizeObserver = new ResizeObserver(function (entries) {
      for (let entry of entries) {
         // once one of the entry changes we want to update the other size too!
         $(".second-col").css('height', $(entry.target).outerHeight());
      }
   });
   
   // We need to pass the actual DOM node, hence the [0]
   resizeObserver.observe($(".first-col")[0]);
});
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.container {
   width: 23.5rem;
   margin: 1rem auto;
}

.first-col {
  background: cornflowerblue;
}

.second-col {
  background: crimson;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="first-col">
    <p>Some content</p>
    <p>Some content</p>
    <button id="add-content">Add content</button>
  </div>
  <div class="second-col"></div>
</div>

Though, I suggest before implementing it like that, that you look into how flex works or simply even min-height might be the proper tool for the issue here. If you’re out of options, feel free to use ResizeObserver, but it’s considered an exotic solution!

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement