0

I have some code that I found online that makes both divs on my website become equal lengths. However, this code only works after the page is refreshed and I have no idea what would cause this. Any help would be appreciated!

 // EQUAL HEIGHTS
$.fn.equalHeights = function(px) {
    $(this).each(function(){
        var currentTallest = 0;
        $(this).children().each(function(i){
            if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
        });
    if (!px && Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
        if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
        $(this).children().css({'min-height': currentTallest}); 
    });
    return this;
};

// just in case you need it...
$.fn.equalWidths = function(px) {
    $(this).each(function(){
        var currentWidest = 0;
        $(this).children().each(function(i){
                if($(this).width() > currentWidest) { currentWidest = $(this).width(); }
        });
        if(!px && Number.prototype.pxToEm) currentWidest = currentWidest.pxToEm(); //use ems unless px is specified
        // for ie6, set width since min-width isn't supported
        if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'width': currentWidest}); }
        $(this).children().css({'min-width': currentWidest}); 
    });
    return this;
};

 // CALL EQUAL HEIGHTS  
 $(function(){ $('#equalize').equalHeights(); });
Janey
  • 1,260
  • 3
  • 17
  • 39

2 Answers2

2

This behavior happens because the plugin was not well written. I've modified it for you and now it should work.

Working DEMO

Plugin script:

// EQUAL HEIGHTS
  $.fn.equalHeights = function(px) {
      var currentTallest = 0;
      $(this).each(function(){
          $(this).siblings().each(function(i){
              if ($(this).height() > currentTallest) { 
                currentTallest = $(this).height();
              }
          });
      });

      if (!px && Number.prototype.pxToEm) {
        currentTallest = currentTallest.pxToEm(); 
      }
      $(this).siblings().css({'height': currentTallest, 'min-height': currentTallest});
      return this;
  };

You can modify the equalWidths plugin to work as this plugin.

Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
0

put all your code in jquery ready function. inside ready function code executes when the DOM is ready

$(document).ready(function(){
//your code
});
chandu
  • 2,276
  • 3
  • 20
  • 35
  • As I mentioned in a comment, `$(function() { ... })` is the same as `$(document).ready(function() { ... })`, and he already put his code in a `$(function() { ... });`. Mentioned in [the API](https://api.jquery.com/jquery/#jQuery3). – Daniël Knippers Apr 27 '14 at 13:12
  • I tried this before posting and it didn't work! Thanks though. – Janey Apr 28 '14 at 10:51