1

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.

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.