This works:
$.fn.center = function () {
this.css("position", "absolute");
this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
return this
};
$('#container').center();
.. but the element stays in the same position if the window is resized, how do I center it with the resize too?
Thanks
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”.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#containerelement.