Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting height based on another elements height over multiple instances in jQuery

I'm using jQuery to obtain the height from one div and add that via css into another

So i have the following layout as an example:

<div class="row">
  <div class="column image">
    <img src="image.jpg" />
  </div>
  <div class="column content">
    <p>Content</p>
  </div>
</div>
<div class="row">
  <div class="column content">
    <p>Content</p>
  </div>
  <div class="column image">
    <img src="image.jpg" />
  </div>
</div>

with the following jQuery

function showHeight( element, height ) {
$( "div.image" ).css("height", height);
}

showHeight( "div", $( ".content" ).height() );

where i would take the height from ".content" & recur that height into ".image"

now obviously this works for say one instance but I'm looking to have this over multiple instances rather than write a function for each.

like image 419
PahPow Avatar asked May 10 '26 03:05

PahPow


1 Answers

You can loop through the .image elements and change its height according to the prev('.content') element.

function updateHeight() {
    // loop through all image elements
    $( "div.image" ).each(function(){
        // get `height` of the previous `.content` element
        var contentHeight = $(this).prev('.content').height();

        // set height
        $(this).css("height", contentHeight);
    });
}

//call one method to update 
updateHeight();

This will only work when the .image comes after .content. I reordered the HTML like this:

<div class="row">
  <div class="column content">
    <p>Content</p>
  </div>
  <div class="column image">
    <img src="image.jpg" />
  </div>
</div>
<div class="row">
  <div class="column content">
    <p>Content</p>
  </div>
  <div class="column image">
    <img src="image.jpg" />
  </div>
</div>

UPDATE:

To find closest .content in any order, change this

var contentHeight = $(this).prev('.content').height();

to

var contentHeight = $(this).prev('.content').height() || $(this).next('.content').height();
like image 56
Maxali Avatar answered May 11 '26 19:05

Maxali