0

I have a function that centers a website vertically:

    function centerWebsite(){
        $vpheight = $(window).height();
        $headerheight = $('header').height();
        $contentheight = $headerheight + $('#content').height();
        $margin = Math.floor(($vpheight - $contentheight)/2);

        $logospacing = $('#logo').css('margin-top');

        if($vpheight > ($contentheight + $logospacing)) {
            $margin = $margin - $logospacing;
        }

        $extendedmargin = $headerheight + $margin;

        $('html').height($vpheight);
        $('body').height($vpheight);
        $('header').css('padding-top', $margin);
        $('#content').css('padding-top', $extendedmargin);
        $('#gallerynav').css('padding-top', $extendedmargin);
    }

This function should be called when the page is ready:

$(document).ready(centerWebsite());

And every time the window gets resized I want to call the same function. I tried to do it like this:

$(window).resize(centerWebsite());

But this won’t work. The solution to this was:

$(window).resize(function() {
    centerWebsite();
});

Do I really need to create a function to call another function?

Afterlame
  • 1,188
  • 2
  • 13
  • 32

2 Answers2

2

By including the parentheses, you're doing a function call. You're looking to pass the function as a reference, in which case, you should pass the variable - without the parentheses.

$(document).ready(centerWebsite);

If you add a console.log inside of your centerwebsite() function, you'll see that it was actually getting called when you called $(document).ready(centerWebsite());.

dtbarne
  • 8,110
  • 5
  • 43
  • 49
2

remove parenthesis:

$(window).resize(centerWebsite);

EDIT NOTE: review this question for some information on callbacks: What are jQuery hooks and callbacks?

Community
  • 1
  • 1
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100