Skip to content

Instantly share code, notes, and snippets.

@jordanneenan
Last active November 2, 2015 01:15
Show Gist options
  • Save jordanneenan/df6430887a3fe0ed81b0 to your computer and use it in GitHub Desktop.
Save jordanneenan/df6430887a3fe0ed81b0 to your computer and use it in GitHub Desktop.
Vertically aligns content with jQuery
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');
}
}
.v-align{
opacity: 0;
transition: opacity 0.5s ease-in-out;
&.show{
opacity: 1;
}
}
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment