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.
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>
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With