Roland
Roland

Reputation: 9691

jQuery | Center Object On Window Resize

With the following function I center an object in the window if the user chooses so :

var showObj = function(obj) {

    setTimeout(function () {
        if(opts.centerObj == true) {
            var cssProps = {
                'position' :'absolute',
                'top' : (($(window).height() - $(obj).outerHeight()) / 2)+'px',
                'left' : (($(window).width() - $(obj).outerWidth()) / 2)+'px'
            }
            obj.css(cssProps).fadeIn('slow');
        }
            else {
                obj.fadeIn('slow');
            }
    }, 1500);

}

But I want to tweak this function or make another one which would center the object if the window resizes.

I've seen I can use this :

$(window).resize(function() {
   obj.css(cssProps);
});

But I think I'm wrong,because nothing happens when I resize the window.

So could someone show me how to create that function that does what I need or tweak the current function so it does that ?

Upvotes: 0

Views: 1318

Answers (2)

Seth
Seth

Reputation: 6260

That depends on where you are calling cssProps. Since it's inside a private function it's not accessible unless you tell it to be. I think the easiest way to do what you want is to pull out the bit of code that creates the JS object and put it into it's own function.

var showObj = function(obj) {

    setTimeout(function () {
        if(opts.centerObj == true) {
            var cssProps = getProps(obj);
            obj.css(cssProps).fadeIn('slow');
        }
        else {
            obj.fadeIn('slow');
        }
    }, 1500);

}

var getProps = function(obj) {

    return {
        'position' :'absolute',
        'top' : (($(window).height() - $(obj).outerHeight()) / 2)+'px',
        'left' : (($(window).width() - $(obj).outerWidth()) / 2)+'px'
    }
}

$(window).resize(function() {
    var cssProps = getProps(obj);
    obj.css(cssProps);
});

Upvotes: 2

Naftali
Naftali

Reputation: 146302

This question was asked and deleted before and here is my solution(10K only)

jQuery.fn.center = function () {

    var $self = $(this), _self = this;
    var window_resize = function(){
        var window_obj = $(window);
        $self.css({
            "position": "absolute",
            "top": (( window_obj.height() - _self.outerHeight()) / 2),
            "left": (( window_obj.width() - _self.outerWidth()) / 2)
        });
    }
    $self.bind('centerit', window_resize).trigger('centerit');
    $(window).bind('resize', function(){
        $self.trigger('centerit');
    });
    return _self;

}


$('div').center();

Fiddle: http://jsfiddle.net/maniator/JeBHJ/

Upvotes: 2

Related Questions