Skip to content

Instantly share code, notes, and snippets.

@clee704
Created May 1, 2014 11:35
Show Gist options
  • Save clee704/a3c567ffb7d9f6bf89d7 to your computer and use it in GitHub Desktop.
Save clee704/a3c567ffb7d9f6bf89d7 to your computer and use it in GitHub Desktop.
// Makes the element be vertically centered in its parent.
angular.module('mygists', [])
.directive('verticalCenter', function ($window, $timeout) {
var win = angular.element($window);
function reposition(element, firstTime) {
var parent = element.parent();
var parentHeight = parent.innerHeight();
var elementHeight = element.outerHeight();
var top = (parentHeight - elementHeight) / 2;
element.css({top: top});
if (firstTime) element.css({opacity: ''});
}
return {
restrict: 'C',
link: function (scope, element) {
element.css({
position: 'absolute',
left: 0,
right: 0,
opacity: 0 // Prevent sudden movement.
});
var repositionBound = _.partial(reposition, element);
var repositionSlowly = _.debounce(repositionBound, 150);
win.on('resize', repositionSlowly);
scope.$on('$destroy', function () {
win.off('resize', repositionSlowly);
});
$timeout(_.partial(repositionBound, true));
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment