An experiment in rounding up list item (<li>) widths to the next grid line. Made for Flash Experiments portal, where I made the list items round up their widths to the end of the frame like in Flash.
The entire thing is accessible so that if JavaScript is turned off, the preset CSS widths will be displayed. Otherwise the JavaScript will replace them if JS is turned on.
This experiment precedes another experiment that adds up the widths of these list items and determine the minimum page width so the list items will not stack upon page shrinking.
Things learned:
element.style.width only sets the width and can't return the value; element.offsetWidth does that.px when setting a style measurement via JS; it works just like in CSS.for loop should be "less than" (<) and not "less than or equal to" (<=). It caused me grief when my Firebug kept saying the item has no properties. That's because I made the loop run past the number of arrays, resulting in a request for nothing.25 Feb 2008.
offsetWidth, among other offsetWhatever properties, which returns (as opposed to "setting") the current value of the element property.px" when defining style measurements via JS.Lots of display-only steps to make sure I'm doing it right. Made/fixed some mistakes along the way.
offsetWidth to the next multiple of 8.for loop condition. (Optional)Here’s the code. Please link back here if you’re using it.
Place this CSS in the head tag.
ul#list1 li{
list-style-type:none;
float:left;
border-left:1px solid #000;
padding:0 16px 0 8px;
width:303px; /* a multiple of 8 minus 1 for the left border */
}
Place this JavaScript in the head tag.
//Redefine the width so Opera won't be confused later when width="auto" renders to 100%
//This also makes all the browsers with JS enabled to read it as auto
document.write("<style type='text/css' >ul#list1 li{width:auto;}</style>");
Place this HTML in the body tag.
<ul id='list1' >
<li class='listItem' >Put list item content here. Repeat <li class="listItem">'s as needed.</li>
</ul>
Place this JavaScript at the end of the body tag.
function doIt() {
var listItem = document.getElementById("list1").getElementsByTagName("li");
for (var i = 0;i < listItem.length;i += 1) {
//Make the math works so your list items line up with the grid.
listItem[i].style.width = 8-((listItem[i].offsetWidth-1)%8) + listItem[i].offsetWidth -26 + "px";
}
}
onload = doIt;