jquery .each with .outerHeight function affects all divs

194 Views Asked by At

I have multiple divs using the same html, with variable heights. I am trying to calculate the height of div .content, then use that value to set the height of the .sections div. Currently, this function is only affecting the last div of its type. How can I make this function reusable so it works on every div on the page?

var currentHeight = 0;
jQuery(document).ready(function() {

    jQuery('.content').each(function() {
      currentHeight = jQuery(this).outerHeight();
    });

    jQuery('.sections').each(function() {
      jQuery(this).css('height', currentHeight/2);
    });

});

Example HTML:

<div class="sections"></div>
  <div class="content">content with a height of 200px</div>
<div class="sections"></div>

other html....

<div class="sections"></div>
  <div class="content">content with a height of 400px</div>
<div class="sections"></div>

So, the first two .sections would get a height of 100px, and the last two .sections would get a height of 200px.

UPDATE: I've found a solution based on Forty3's answer! Can this be written more DRY though?

Forty3's solution worked for me, with some minor tweaking:

// With the .content FOLLOWING the .section - use the following:
jQuery(document).ready(function() {

    jQuery('.bigImageSections').each(function() {

      var ic = jQuery(this).next('.translatedContent');
      if (ic.length > 0) {
        jQuery(this).css('height', jQuery(ic).outerHeight() / 2);
      }

      var ict = jQuery(this).prev('.translatedContent');
      if (ict.length > 0) {
        jQuery(this).css('height', jQuery(ict).outerHeight() / 2);
      }

    });
});
1

There are 1 best solutions below

1
Forty3 On

Run through your .section elements recalculating their height based on the height of the inner .content element:

// If the .content was inside the .section - use the following
jQuery(document).ready(function() {

    jQuery('.sections').each(function() {
      var ic = jQuery('.content', this);
      if (ic.length > 0) {
        jQuery(this).css('height', jQuery(ic).outerHeight() / 2);
      }
    });
});

// With the .content FOLLOWING the .section - use the following:
jQuery(document).ready(function() {

    jQuery('.sections').each(function() {
      var ic = jQuery(this).next('.content');
      if (ic.length > 0) {
        jQuery(this).css('height', jQuery(ic).outerHeight() / 2);
      }
    });
});

Edit: Forgot to divide by 2.

BTW: I noticed in your sample HTML, your .content was not contained within your .section .. was this intentional? If so, are you anticipating that the .section elements be intelligently sized based on preceding or following .content elements?