Search code examples
jqueryjquery-pluginscenteringwindow-resize

Rerun jquery plugin instance on window resize


I want to build a plugin that will be centerizing stuff for me, but I wanted to automate rerun every instance of it after window resizing, here's some (not-working on window resize) code:

$.fn.centerize = function(){
    var divWidth = this.width(),
        screenWidth = $(window).width(),
        margin = (screenWidth - divWidth)/2;

    this.css({'margin-left':margin + 'px', 'margin-right': margin + 'px'});
    $(window).resize(function(){
        this.centerize();
    });
}

All what I would like to do, is to run this plugin only once on some div elements, e.g.:

$('.myCenteredDiv').centerize();

And if I resize the browser window, it should recalculate margins and set new ones. I don't want to add somewhere additional code like this:

$(window).resize(function(){
    $('.myCenteredDiv1').centerize();
    $('.myCenteredDiv2').centerize();
    $('.myCenteredDiv3').centerize();
});

Is that possible? Any suggestions will be appreciated.


Solution

  • Problem with context:

    $(window).resize(function(){
        this.centerize();
    });
    

    Try to assign 'this' to another temporary variable:

    $.fn.centerize = function(){
        var divWidth = this.width(),
            screenWidth = $(window).width(),
            margin = (screenWidth - divWidth)/2,
            _this = this;
    
        this.css({'margin-left':margin + 'px', 'margin-right': margin + 'px'});
        $(window).resize(function(){
            _this.centerize();
        });
    }
    

    Or you can try to use $.proxy for binding context in another scope:

    $.fn.centerize = function(){
        var divWidth = this.width(),
            screenWidth = $(window).width(),
            margin = (screenWidth - divWidth)/2;
    
        this.css({'margin-left':margin + 'px', 'margin-right': margin + 'px'});
        $(window).resize($.proxy($.fn.centerize, this);
    }