Adjust the height of a div to match the tallest element in the same row using jQuery and Javascript

I need to display multiple rows of products, each row containing 4 products. The code snippet below shows an example with only 1 product. To create a row with 4 products, the code for

<div class='col-xs-6 col-sm-3 col-md-3'>
needs to be repeated 3 more times within <div class="row">:

<div class="row">
  <div class='col-xs-6 col-sm-3 col-md-3'>
      <div class='thumbnail'>
        <div class = 'matchHeight'><a href='www.url.com'><img src='product.jpg' alt='product'></a></div>
        <div class='caption' style = 'text-align: center;'>
          <div style = 'height: 60px;'>Product Name<br />
            £9.99</div>
          <p style = 'padding-top: 10px;'><a href='www.url.com' class='btn btn-primary btn-thumbp' role='button'>View</a>
        </div>
      </div>
    </div>          
</div>

The jQuery function below calculates the height of each 'matchHeight' div, finds the tallest height, and then sets all divs to the same height:

boxes = $('.matchHeight');
maxHeight = Math.max.apply(
Math, boxes.map(function() {
    return $(this).height();
}).get());
boxes.height(maxHeight);

My webpage consists of multiple <div class="row"> elements. Is there a way to make the above function run independently for each row? I want the height calculation to be specific to each row and not affect other rows on the page.

Answer №1

Check out the following JavaScript snippet:

$('.container').each(function(){
  elements = $(this).find('.equalHeight');
  tallestHeight = Math.max.apply(
  Math, elements.map(function() {
    return $(this).height();
  }).get());
  elements.height(tallestHeight);
});

Answer №2

Here is an updated and more efficient version of the answer code for neatness and better performance. My team member attempted to use the codePen version directly, but I had to optimize it for production, so I'm sharing the improved version to save time and effort for future users:

JavaScript:

var adjustHeight = function (container) {
    var elements = $(container).children();
    if (elements.length) {
        var currentTallest = 0,
            currentRow,
            row;

        elements.each(function () {
            var $element = $(this);
            var topPos = $element.position().top;
            $element.height('auto');

            if (currentRow != topPos) {
                row && row.length && row.height(currentTallest);

                row = $element, currentRow = topPos, currentTallest = $element.height();
            } else {
                row = row.add($element);
                currentTallest = currentTallest < $element.height() ? $element.height() : currentTallest;
            }

            if (row.length > 1) {
                row.height(currentTallest);
            }
        });
    }
};

adjustHeight($('.equal-height'))

HTML:

<div class="equal-height">
    <div class="child-to-resize-1"></div>
    <div class="child-to-resize-2"></div>
    <div class="child-to-resize-3"></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

Tips for invoking the export function in node.js using sequelize

Need help with calling the function (search_all_user) to export in node.js using sequelize module.exports = function (sequelize, Sequelize, DataTypes) { var User = sequelize.define('user', { id: {type: Sequelize.INTEGER, unique: true, prima ...

Adding div elements using checkbox switch

In this code snippet, my aim is to display costs based on checkbox selection and generate corresponding totals in the bottom row when the checkboxes are toggled. The goal is to allow users to choose relevant items and have the total cost calculated accordi ...

Using Jquery to transfer text from a form to a DIV and ensuring the final character is verified

Users can input their name on my HTML form, which will then be displayed in a DIV as part of a book title. The book title includes apostrophes (e.g. Amy's Holiday Album). However, if the user's name ends with an S, I do not want the apostrophe ...

Loop through the json array

Looking to access JSON array values using .each Here's how I populate the array values: $allRecords= array(); while($row = mysql_fetch_array($result)){ $oneRecord[] = array("orderNo"=>$row['order_no'],"orderDate"=>$row[&a ...

Image of outer space enclosed by a circular boundary

Check out this fiddle I created here. It's a simple concept of an image inside a red circle. Is there a way to add some spacing around the image within the circle? This is the markup I currently have: <div style=" width: 50px; he ...

Creating a unique carousel design using only CSS in Bootstrap

Trying to create a CSS effect to enhance Bootstrap, I noticed that it only works correctly when clicking the right arrow. Whenever I click the left one, nothing happens. I'm not sure where I made a mistake, can anyone help me spot it? Thanks in advanc ...

Wait for NodeJS to finish executing the mySQL query

I am attempting to send an object from the controller to the view. To keep my queries separate from the controller, I am loading a JS object (model). My model structure is as follows: function MyDatabase(req) { this._request = req; this._connection = ...

Ways to modify the color of mat-icon within an input field using Angular 6

Here is the code from my HTML file: <div class="input-field"> <div> <input type="text" id="name" required email/> <label for="name">Email: <mat-icon svgIcon="mail" class="change-color"></mat-icon> &l ...

Ways to structure this updateone query for mongoose formatting

UPDATE: After making adjustments to the query using arrayFilters recommended by someone here, the query is returning success. However, the values in the database are not being updated. I am attempting to update specific fields within a MongoDB collection ...

Issue with parameter functionality not working as expected

This code snippet is not functioning as expected. I am trying to extract and print the values from the URL parameter file:///C:/Users/laddi/Desktop/new%201.html?t=vindu&b=thind function GetURLParameterValue(param) { var pageURL = window. ...

Using jQuery to validate forms in CodeIgniter framework

JavaScript: $(document).ready(function(){ $('#username').change(function(){ var username = $('#username').val(); $('#usernamemsg').html('<img src="<?php echo ...

Is it possible to retrieve the index of a particular element within an array during an update operation in MongoDB?

After executing the following update statement const result = await Post.updateOne({_id: postId},{ $pull: {reacts: {publisher: req.query.publisher}}, $inc: {postPoints: - reactsEnum[ReactType]} }); I am interested in obtaining the ...

When using jQuery's POST method, the "done" event is triggered, however, no data is being sent

I've been working on implementing AJAX form submission and wrote a function to handle it when the button is clicked: function putUser() { $('button#putUser').on('click', function() { var user = $('input#user' ...

Eliminate the excess space at the bottom of rows in Materialize CSS

Having difficulty adjusting the padding between two rows in materializecss Troubles with Padding https://i.sstatic.net/KFe1w.png Seeking to eliminate the bottom padding. Managed to remove left and right padding with the following code: <div class="c ...

404 error: API endpoint inexistent despite being present

I am encountering an issue while attempting to retrieve a product by its ID. Interestingly, when I tested this using Postman, everything worked flawlessly without any errors. However, when I tried to fetch the data using Angular, it kept returning a 404 no ...

The element 'x' is implicitly bound with a type of 'any'

I've been exploring the world of Nextjs and TypeScript in an attempt to create a Navbar based on a tutorial I found (). Although I've managed to get the menu items working locally and have implemented the underline animation that follows the mou ...

Tips for loading a webpage with optimal speed and efficiency

I am inspired by the sleek design of Apple's website and want to replicate some of its features in my project (best viewed on FF, Chrome, Safari): Initially, the page appears empty except for the header - but the final height of the page is already ...

How can I successfully transfer all user information when the edit button is clicked?

A new display page has been developed using php to show all user records in a table. The page includes delete and edit buttons for managing users. While the delete option is working fine, there is an issue with getting the edit button to function correctly ...

unable to show image retrieved from JSON data

Looking to showcase the data from my JSON objects, which are displayed in 2 images below https://i.stack.imgur.com/yhqFy.png https://i.stack.imgur.com/DUgFO.png In the data, I have properties like c_name, max_slots, and an array slots. Within the array, ...

Accessing the SQL database using Cypress

I am attempting to establish a connection with an SQL database using Cypress following the guidelines provided in the NPM guide. I have ensured that all dependencies are installed as specified, however, when I run the following query: cy.sqlServer('S ...