Search code examples
javascriptjquerycssmethodswindow-resize

Call function on window resize within jquery method


I've created a tiny jquery-method to center an element vertically and horizontally:

(function ($) {
    $.fn.center = function() {
            $(this).css({
                position: 'absolute',
                left: ($(window).width() / 2) - $(this).outerWidth(true) / 2,
                top: ($(window).height() / 2) - $(this).outerHeight(true) / 2
            });

            return this;
    }
}(jQuery));

Now I'm able to center a specific element:

$('div').center();

As far as that everything works perfectly. But now i'd like to re-center the element on window.resize.

Of course, I could just call the method like this:

$(function onresize(){
    $('div').center(); 
    $(window).on('resize', onresize);
});

But i do not want it like this. I would like to manage this within the method (so that i can call the method normally - like in the second code-area of my question).

I've tried the following:

(function ($) {
    $.fn.center = function() {

        $( window ).resize(function() {
            $(this).css({
                position: 'absolute',
                left: ($(window).width() / 2) - $(this).outerWidth(true) / 2,
                top: ($(window).height() / 2) - $(this).outerHeight(true) / 2
            });
        });

        return this;

    }
}(jQuery));

But this doesn't work. Why? Thanks in advance! :)


Solution

  • Now it hit me. The scope is not right anymore. Change it to the following

    (function ($) {
        $.fn.center = function() {
            $this = $(this);
    
            $( window ).resize(function() {
                $this.css({
                    position: 'absolute',
                    left: ($(window).width() / 2) - $this.outerWidth(true) / 2,
                    top: ($(window).height() / 2) - $this.outerHeight(true) / 2
                });
            });
    
            return this;
        }
    }(jQuery));