I am trying to set margin of the id:main dynamically by obtaining viewport width. I have numerous blocks of same width in the page. So, i want to fit as many blocks as possible and centre them by dynamically calculating the remaining width. the block is of size 240px, 20px of padding
I have tried two codes, i’m stuck at this for a while.
var width=$(window).width()
var stickies=Math.floor(width/240); //* calculate how many can fit in a row
var mrg=(width-(stickies*240)-20);//*calculating remaining width
var mrg=(width-(stickies*240)-20)/2;
var el1=$('#main');
var el2=$('#main');
el1.css('margin-left',mrg+'px');
el2.css('margin-right',mrg+'px');
var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body') [0],x=w.innerWidth||e.clientWidth||g.clientWidth;
var stickies=Math.floor(var x/240);
var mrg=(var x-(var stickies*240)-20)/2;
var el1=$('#main');
var el2=$('#main');
el1.css('margin-left',mrg+'px');
el2.css('margin-right',mrg+'px');
Short Version
you should need something along those lines
Long Version
your code needs a lot of fixing up.
needs to change to
because at the moment u are not selecting anything. you need to place your selector in quotes.
also i dont understand why u are using 2 variables for the same element. you could do something like
or something along those lines.
Finally,
The 2nd line will overwrite the 1st line. Is this a typo or are you trying to do something here?