Last active
November 2, 2015 01:15
-
-
Save jordanneenan/df6430887a3fe0ed81b0 to your computer and use it in GitHub Desktop.
Vertically aligns content with jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.v-align{ | |
opacity: 0; | |
transition: opacity 0.5s ease-in-out; | |
&.show{ | |
opacity: 1; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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