Joined June 2013
·
Posted to
Perfectly Center Inside Entire Page with jQuery
over 1 year
ago
instead of calling jQuery you should cache these elements outside your resize event handler. traversing a large dom might be inefficient so doing it only once might improve the performance!
var $window = $(window);
var $container = $('.container');
var $centerContainer = $('.centered-container');
// you should also cache the size of the centered container if its size never changes
// var centerContainerWidth = $centerContainer.outerWidth();
// var centerContainerHeight = $centerContainer.outerHeight();
$window.resize(function(){
var windowWidth = $window.width();
var windowHeight = $window.height();
$container .css({
height: windowHeight,
width: windowWidth
});
$centerContainer.css({
position: 'absolute',
left: (windowWidth - $centerContainer.outerWidth()) / 2,
top: (windowHeight - $centerContainer.outerHeight()) / 2
});
});
$window.resize();
Achievements
29 Karma
0 Total ProTip Views

Forked
Have a project valued enough to be forked by someone else

Charity
Fork and commit to someone's open source project in need

Cub
Have at least one original jQuery or Prototype open source repo
you could also add the following code into your constructor
this automatically creates a new instance if you call
Button("test", ...)
without the new keyword