Skip to content Skip to sidebar Skip to footer

Center On Resize Too

This works: $.fn.center = function () { this.css('position', 'absolute'); this.css('top', ($(window).height() - this.height()) / 2 + $(window).scrollTop() + 'px'); this

Solution 1:

You would need to execute that code in the windowresize event. But, if the browser is resized this event fires huge! So it's in general a good idea to create a little "balancer".

$(window).bind('resize', function() {
    var that = this;        

    if(!('balancer'in that) ) {
        that.balancer = setTimeout(function() {
            $('#container').center();
            delete that.balancer;
        }, 200);
    }
});

This will absorb the many events that are fired when resizing the browser window. In fact, it only calls the .center() at a maximum of 200ms. You probably should even increase that value and cache the node reference to the #container element.

Solution 2:

EDIT::

giving percentage to top and left can put at center. but this bad ... really really bad.

    $.fn.center = function () {
        $(this).css({'position': 'absolute',
                     'top': '40%',
                     'left': '40%'
                    });
    };

    $(function (){
        $('#container').center();
    })

On jsfiddle.

Post a Comment for "Center On Resize Too"