jordanneenan
4/7/2015 - 10:16 AM

Vertically aligns content with jQuery

Vertically aligns content with jQuery

function vAlign(){
  if($('.v-align').length){
    var $vaChild = $('.v-align');
    $vaChild.each(function(){
      var vaChildHeight = $(this).height();
      var vaParentHeight = $(this).parent().height();
      var topOffset = (vaParentHeight - vaChildHeight) / 2;
      $(this).css('paddingTop', topOffset).addClass('show');
    });
  }
}

//--------- on window load ---------
$(window).load(function(){
    vAlign();
});

//-------- on window resize --------
$(window).resize(function(){
    vAlign();
});

//I have also had to call the function on resize after a delay, can't remember whether it was necessary or whether it was for something specific but you can get the code here: http://stackoverflow.com/questions/5489946/jquery-how-to-wait-for-the-end-of-resize-event-and-only-then-perform-an-ac

.v-align{
    opacity: 0;
    transition: opacity 0.5s ease-in-out;

    &.show{
        opacity: 1;
    }
}
var rtime;
var timeout = false;
var delta = 200;
$(window).resize(function() {
    rtime = new Date();
    if (timeout === false) {
        timeout = true;
        setTimeout(resizeend, delta);
    }
});

function resizeend() {
    if (new Date() - rtime < delta) {
        setTimeout(resizeend, delta);
    } else {
        timeout = false;
        alert('Done resizing');
    }               
}