Add padding on page load and resize

1k Views Asked by At

I calculate the padding of an element and add it on resize. Now, I would like to add it also on page load. How can I do that?

Live demo

$(window).resize(function () {
    var widthWindow = $(window).width();
    var widthContainer = $("#container").width();
    var calculatePadding = (widthWindow - widthContainer) / 2;
    $("#container").css({
        "padding-top":calculatePadding,
        "padding-bottom":calculatePadding
    });
}).resize();
2

There are 2 best solutions below

0
Nagaraju On

You could do it this way:

<body onload="resize()">

In Javascript:

function resize(){
    //write your stuff here
}

(OR) the jQuery way

$(document).ready(function(){
    resize();
});
4
enno.void On

Just bind your handler to the load event:

var handler = function () {
    var widthWindow = $(window).width();
    var widthContainer = $("#container").width();
    var calculatePadding = (widthWindow - widthContainer) / 2;
    $("#container").css({
        "padding-top":calculatePadding,
        "padding-bottom":calculatePadding
    });
};

$(window).resize(handler)
$(window).load(handler)

Or a bit more elegant in my opinion:

$(window).on('load, resize', handler)