galexy
galexy

Reputation: 343

Setting width using .css method in jQuery with window re-size as condition

In my template I want to set my #wrapper container width dynamically using jQuery, so for any screen resolution, #wrapper width will be screen width - 200.

var _width= ($(window).width() - 200) 
$("#wrapper").css("width",_width);  

After setting this value, I want to change width dynamically on window re-size. I use the following jQuery:

$(window).bind('resize', function() {
    var _width_prcnt = (($(window).width()- (200)/($(window).width()/100) );
    $('#wrapper').stop(false,true).animate({
        'width':_width_prcnt+ '%'
    });
}); 

I think this doesn't work properly. How can I use an if-else statement so that the width is set once, and animating the width works only if there is window re-size?

Upvotes: 1

Views: 584

Answers (3)

csaron92
csaron92

Reputation: 1045

You should resize your window only with css. The window with:200px is easy with margin.

#wrapper{
min-width:500px;
margin:0 100px;
}

This is also centered.

Upvotes: 2

Maen
Maen

Reputation: 10698

You could use CSS3's calc() to achieve this (doc):

#wrapper{
    width:calc(100% - 200px);
    margin: 0 100px; //If you want the content centered
}

With #wrapper being the direct child of an element whose width is the window's width.

Please see this chart on caniuse.com for browser compatibility, and this fiddle for a working example.

Upvotes: 1

asifrc
asifrc

Reputation: 5841

jQuery .resize() should work, I just answered another question a few minutes ago about it at Set CSS aspect ratio to the inverse of width?. Check my answer + the linked fiddle to see if it gives you the functionality you're looking for. Let me know if my answer works for you, or let me know how .resize() doesn't fit and I'll try to give a better answer.

Upvotes: 1

Related Questions