Is it possible to dynamically adjust div height using on resize event?

In my current setup, I have two separate divs on the left and right sides. The issue arises when the height of the left div exceeds the height of the right div. In such cases, the function adjusts the heights to be equal and hides any excess text in the left div. While this solution works well in general, the problem arises when I resize the window or test the layout on different screen sizes. The height of the left div gets messed up and does not revert to its original state as expected.

For a visual demonstration of the issue, you can visit this link. Simply switch between various screen sizes and exit responsive mode to observe the problem.


        var leftContainer = document.getElementById('overflow_text')
        var rightContainer = document.getElementById('offset_height')
        var readToggle = document.getElementById('toggle_text')
        var elem = document.querySelector('.readMore')
        var fullText = elem.textContent;
        var truncated = false;
        var rightOffsetHeight = rightContainer.offsetHeight;
        var leftOffsetHeight = leftContainer.offsetHeight;
        console.log(leftOffsetHeight)
        console.log(rightOffsetHeight)

        function mounted() {
          if (leftOffsetHeight > rightOffsetHeight) {
            leftContainer.style.height = rightOffsetHeight + "px"
            readToggle.style.display = 'block'
            readToggle.innerHTML = 'Read More'
            while (leftContainer.scrollHeight > leftContainer.offsetHeight) {
              var wordArray = leftContainer.innerHTML.split(' ');
              wordArray.pop();
              leftContainer.innerHTML = wordArray.join(' ') + '...';
              truncated = true
            }
          } else {
            readToggle.style.display = 'none'
          }
        }

        function showText() {
          if (truncated) {
            leftContainer.innerHTML = fullText
            leftContainer.style.height = 'auto'
            readToggle.innerHTML = 'Read Less'
            readToggle.style.position = 'relative'
            truncated = false
          } else {
            leftContainer.style.height = rightOffsetHeight + "px"
            while (leftContainer.scrollHeight > leftContainer.offsetHeight) {
              var wordArray = leftContainer.innerHTML.split(' ');
              wordArray.pop();
              leftContainer.innerHTML = wordArray.join(' ') + '...';
              readToggle.innerHTML = 'Read More'
              truncated = true
            }
          }
        }

        function watchSize() {
          var w = window.outerWidth;
          var h = window.outerHeight;
          console.log(w)
          console.log(h)
        }
      

        #toggle_text {
          cursor: pointer;
        }
        #offset_height {
          font-size: 16px;
        }
      

        <body onLoad='mounted()' onresize='watchSize()'>
        <p id="demo"></p>
        <div class="container">
        <div class="row">
        <div class="col-md-6">
        <p id='overflow_text' class="readMore">Lorem ipsum dolor sit amet... // The rest of the HTML code is intact but omitted for brevity.
      

If anyone has a solution to address this issue, I would greatly appreciate it. Thank you in advance.

Answer №1

Here is a helpful code snippet I use to dynamically adjust the height of a div element when the window is resized:

new ResizeSensor(jQuery('#targetDiv'), function(){ 
console.log('The dimensions of the content have changed');
});

Answer №2

Check out this JavaScript code snippet:

<script>
function adjustDivSizes() {
var mainDiv = document.getElementById('main').offsetHeight;
var sidebarDiv = document.getElementById('sidebar').offsetHeight;
if (sidebarDiv > mainDiv) {
    mainDiv = sidebarDiv;
    document.getElementById('main').style.height = document.getElementById('sidebar').style.height = mainDiv + 'px';
} else {
    sidebarDiv = mainDiv;
    document.getElementById('sidebar').style.height = document.getElementById('main').style.height = sidebarDiv + 'px';
}
}
window.onload = adjustDivSizes;
</script>

For more information, feel free to visit this link.

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

How to organize PHP JSON data using JavaScript

I need help sorting PHP JSON data from a multidimensional array using JavaScript or jQuery. Here is my PHP code: $array = array(); $x = 0; while($row = $get_images->fetch_assoc()){ $name = $row['name']; $image_type = $row['image_ ...

The oddity of a lone quotation mark trying to break

var x = "Test \'" > undefined var y = "Test '" > undefined x === y > true x > "Test '" https://i.stack.imgur.com/ZrHo5.jpg Aha! Both of these strings are actually equal (as shown in the example code) - but why is that the ...

Utilizing a switch statement for efficiently loading multiple objects within a Three.JS framework

Currently, I am working on a web 3D model viewer that utilizes Three.JS. My goal is to enable users to select different models from a dropdown list using dat.GUI. To achieve this, I have been experimenting with a switch statement, drawing inspiration from ...

JavaScript validation function stopping after the first successful validation

Script: NewsletterValidation.js function formValidation() { var fname = document.getElementById('firstName').value; var lname = document.getElementById('lastName').value; var pnumber = document.getElementById('phoneNumb ...

React JS: Component failing to render

My react component is not rendering and I can't find any bugs. The problem arises when I set the isLoggedIn state to "true", resulting in my HeroSlide not rendering If isLoggedin = false, then: https://i.sstatic.net/JoDSn.jpg If isLoggedIn = true, t ...

Does angular have a feature comparable to JavaScript's .querySelectorAll()?

I developed an inventory calculator in JavaScript that provides item count based on weight. The calculator has 4 inputs, and now I'm looking to replicate the same functionality using Angular. Is there a method in Angular similar to .querySelectorAll() ...

Unlocking the secrets of accessing HashMaps containing Objects post conversion to JSON

In my Java code, I have created a data structure using HashMap that stores PriceBreak objects along with corresponding PricingElement ArrayLists. This data has been sent to the client via GSON. However, when I try to access this object in JavaScript and lo ...

What is the proper way to implement a $scope.$watch for a two-dimensional array in AngularJS?

Having trouble implementing an Angular watch on a multidimensional array I've got a screen where users can see two teams (outer array) with team sheets (inner array) for each team. They can drag and drop players to change the batting order. The batt ...

The hyperlink is not functional

I'm embedding PHP code within an HTML page and using an href link, but it's not working. Here's the HTML+PHP code snippet: <div class="panel-body"> <div class="row"> <div class="col-md-12 space20"> & ...

The AJAX request encountered an unexpected failure that cannot be identified (Using jQuery)

Are you facing issues with a service that returns JSON data? Check out this URL: If you're attempting a simple AJAX request, here's some sample code to get you started: $.ajax({ type: "get", url: "http://api.drag2droid.shamanland.com/ca ...

Tips for efficiently storing and accessing data obtained from the "RESTBuilder" tool on the Total.js platform

After stumbling upon this informative tutorial on how to build a cryptocurrency comparison site with VueJs, I was inspired to create a single-page application using the total.js platform. My goal is to fetch the list of coins from the "coinmarketcap.com" A ...

Resetting the selected options in AngularJS dropdown lists

Utilizing ng-repeat in my HTML code to iterate over a JavaScript array and displaying it within a selection. I am trying to achieve the functionality of clearing all selected data from these dropdown lists when a button is clicked. Snippet of HTML: <d ...

Utilizing JQuery toggle feature to display extra content

Having some trouble with my JQuery toggle/collapse function. I added my own class "timelineEventWide" but it's not working as expected. As a JavaScript beginner, could someone please help me with the correct syntax? Thank you! e(".expandAll").toggle( ...

How can I fetch data from a ManyToMany jointable using Typeorm?

Is there a way to retrieve the categories associated with posts when fetching user data? Data Models: @Entity() export class Category extends BaseEntity { @PrimaryGeneratedColumn() id: string; @Column() name: string; @Column() description: s ...

Can anyone suggest a reliable method for comparing two dependencies trees generated by the `npm list` command?

Prior to launching the project, it is crucial to analyze the updated dependencies that could potentially affect other pages. Utilizing the npm list command can help generate a comprehensive tree of all dependencies. What is the most efficient way to comp ...

ui-router: Issue with ui-sref causing font color to remain unchanged

I've been trying to customize the font color of a navigation link using ui-router's ui-sref functionality, but I'm facing an issue. While I can change the background color by adding it to the .active class in my CSS, the font color remains u ...

Is it possible to combine ng-switch and ng-if directives in Angular?

I attempted to combine the angular ng-switch and ng-if directives, but it doesn't seem to be functioning properly. Here is what I tried: <div data-ng-if = "x === 'someValue'" data-ng-switch on = "booleanValue"> <div data-ng-swit ...

conceal a targeted section from the bottom of the iframe

I have a website embedded inside an iframe for use in a webview application. <body> <iframe id="iframe" src="http://www.medicamall.com"></iframe> </body> This is the CSS code: body { margin:0; padding:0; height:10 ...

Issues with AJAX requests failing to fire with the latest version of jQuery

A small script I have checks the availability of a username in the database, displaying "taken" if it's already taken and "available" if it's not. The code below works perfectly with jQuery v1.7.2. However, I need to update it for jQuery v3.2.1. ...

Retrieve information from the existing URL and utilize it as a parameter in an ajax request

Currently, I am working on a website with only one HTML page. The main functionality involves fetching the URL to extract an ID and then sending it to an API using an AJAX call. Upon success, the data related to the extracted ID is displayed on the page. H ...