JS element justification
March 4, 2008 by m.wallace
Comments Off
So in an over-exuberant (and low-sleep) moment, I coded this one up. Say ya wanna have 5 elements on a page evenly spaced out, but you can’t depend on .. anything. Under normal circumstances a sane person would just use a table, with text-align:center & td.padding. Nope. Not me. I do things the hard way:
<script>
function justifier(par){
ulist=document.getElementById(par);
plain=0;
count=0;
/* determine widths for padding. Must set paddings to 0 for an accurate count */
for(i=0;i<ulist.childNodes.length;i++){
if(ulist.childNodes[i].nodeType==1 && ulist.childNodes[i].nodeName=="LI"){
pad(ulist.childNodes[i],0);
plain+=parseInt(ulist.childNodes[i].offsetWidth);
count++;
}
}
wide=ulist.offsetWidth;
x=parseInt((wide-plain-count)/(count*2)); //due to FF, count !=ulist.childNodes.length
//alert("w:"+wide+" cw:"+plain+" ="+(wide-plain)+"/"+count+" pad:"+x);
/* change paddings: */
for(i=0;i<ulist.childNodes.length;i++){
if(ulist.childNodes[i].nodeType==1 && ulist.childNodes[i].nodeName=="LI"){
mainMenuItem=ulist.childNodes[i];
pad(mainMenuItem,x);
}
}
}
function pad(ele,x){
ele.style.paddingLeft=x+"px";
ele.style.paddingRight=x+"px";
}
</script>
<style>
#list{
width:40%;
border:1px red solid;
}
ul{
padding:0px;
margin:0px;
float:left;
list-style-type:none;
}
li{
padding:0px;
margin:0px;
float:left;
list-style-type:none;
}
</style>
<body onload="justifier('list')" onresize="justifier('list')">
<ul id="list">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</body>