xan
xan

Reputation: 4696

Adjusting width of page using Javascript

My page is of the following structure:

<container>
   <header>
   <main-content>
   <footer>
</container>

I'm adjusting the width of the container using javascript by the following code:

function getPageSize() {
            var de = document.documentElement;
            var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
            var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
            arrayPageSize = [w, h];
            return arrayPageSize;
        }
        $(document).ready(function () {
            var page = getPageSize();
            var x = page[0];
            var y = page[1];
            $("#container").css({width: (x) + 'px'}); 

EDIT

Now, I'm using a slider [setting a div to width 9999em and inserting slider elements in it].The page opens good when the browser window is maximized.

Is there any better way of achieving this for different resolutioned-devices, so that when I press (Ctrl)+(-), the page remains gets smaller revealing the other screens. How can I make the page remain in the middle, without revealing the other screens.

Here is the image: enter image description here

One thing that I experimented was: If I set the width of the container element in px, I get the desired results. But, I can't set the width of the container (whose width I'm setting using ($(window).width()) beforehand, as it'll depend upon the different devices.

Upvotes: 1

Views: 173

Answers (3)

user234932
user234932

Reputation:

You should take a look at some of the responsinve CSS frameworks, which solve prblems like this for various devices. One example is Bootstrap (very popular right now), but there are others.

Anyhow, the way I keep things cenetered when I want absolute control in Javascript/jQuery is this:

var desiredWith = x;
var pad = ($(window).width() - desiredWidth) / 2;
$(selector).css({position: 'absolute', left: pad, right: pad, width: auto;});

This doesn't always (usually?) work in some of the older browsers, but I work at a company that doesn't target them, so I can't tell you which ones break.

Upvotes: 0

Rahul garg
Rahul garg

Reputation: 9362

what about:

width: auto

or

width: 100%

since it is most parent container of your page...

After Edit made to questions: To make your container always 'centered' instead of left aligned, you can use:

margin: auto

to make the container always in center positioned..

Upvotes: 2

Matija Milković
Matija Milković

Reputation: 2458

How about:

$(window).resize(function() {
  var pageSize= $(window).width();
   $("#container").css({width: (pageSize) + 'px'}); 
});

Upvotes: 2

Related Questions