Making Height Recalculate on Resize

Issue

PLEASE SEE CODEPEN FOR CLARITY: http://codepen.io/geochanto/pen/LGNWML

var maxHeight = 0;

$('li a').each(function() {
    maxHeight = maxHeight > $(this).outerHeight() ? maxHeight : $(this).outerHeight();
    var linkHeight = $(this).outerHeight();
    var halfLinkHeight = parseInt(linkHeight / -2);
    $(this).  css({
   'margin-top' : halfLinkHeight,
   'height' : maxHeight
    });  
});

$("li").css("height", maxHeight);

So I have this code that calculates height of links, then makes them all the height of the tallest one, and adds some negative margin on top for purposes of vertically middle-aligning them all inside their respective parents. Everything works as I want, except, I’ve been trying to get this height to recalculate and apply to <li> and <a> on window resize with various methods but none worked.

I’ve tried these, but perhaps my syntax was wrong, idk:

  1. How to create a jQuery function (a new jQuery method or plugin)?
  2. Run Jquery function on window events: load, resize, and scroll?
  3. How to call a function in jQuery on window resize?

Solution

I got it working for you here: http://codepen.io/anon/pen/RraVZE

It took some changes to your css and your javascript.

I removed the absolute positioning from your a tag:

a {
  display: block;
  padding: 10px;
  margin-left: 50px;
  font-size: 16px;
  line-height: 1.2;
  font-family: "montserrat", Arial, Helvetica, sans-serif;
  text-transform: uppercase;
  color: #193170;
  text-decoration: none;
  word-wrap: break-word;
}

And modified your JavaScript:

$(document).ready(function() {

  var maxHeight = 0;

  function calculateHeight() {
    $('li a').each(function() {
      maxHeight = maxHeight > $(this).outerHeight() ? maxHeight : $(this).outerHeight();
    });
    $("li").css("height", maxHeight);
    centerText();
  }

  function centerText() {
    $('li a').each(function() {
      var linkHeight = $(this).outerHeight();
      var halfLinkHeight = parseInt((maxHeight - linkHeight) / 2);
      $(this).css('margin-top', halfLinkHeight);
    });
  }

  $(window).resize(function() {
    calculateHeight();
  });

  calculateHeight();

});

Answered By – Fraser Crosbie

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.