Adam
Adam

Reputation: 29019

Height does not change on resize() in jQuery

I have 4 div container with different height. I want that all of them have the same height whenever I load the page or resize the window. I gave each div the class requirement and tried the following jQuery code:

<script type="text/javascript">

        $(document).ready(adjustRequirement);
        $(window).resize(adjustRequirement);

        function adjustRequirement(){
            var maxHeight = -1;

            $('.requirement').each(function() {
                maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
            });

            $('.requirement').each(function() {
                $(this).height(maxHeight);
            });
        }
</script>

Now this works whenever I load the page (or refresh with F5), but it does not work when I resize the window. What am I doing wrong? Here is a fiddle.

Upvotes: 2

Views: 1903

Answers (2)

valepu
valepu

Reputation: 3315

this happens because you have set a fixed height on the first run of the function, this way the height will always be the same for every div. Since divs have by default overflow: visible the text will be shown even though it goes outside the div.

Try this, i have added a line where it resets the div's height so that it adjusts to fit the content $(this).css('height', 'auto');:

  $(document).ready(adjustRequirment);
  $(window).resize(adjustRequirment);

  function adjustRequirment(){
      var maxHeight = -1;

      $('.requirement').each(function() {
          $(this).css('height', 'auto');
          maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
      });

      $('.requirement').each(function() {
          $(this).height(maxHeight);
      });
  }

Upvotes: 4

MKAD
MKAD

Reputation: 457

You also can use jquery-match-height. Just download and implement jquery.matchHeight.js

$(document).ready(function() {
  $(function() {
    $('.requirement').matchHeight();
  }
});

it very easy to use and it works also on rezise.

Upvotes: 1

Related Questions