Floats and Iterators

May 17, 2010
Episode 25
Nick reveals the exciting conclusion to last week's cliffhanger and explores the mythical float property. Then, Jim unravels the confusion surrounding JavaScript iterators.
Spotlight

Thanks to those who make Doctype possible!

Floats

Years ago when designers and developers transitioned from tables to CSS based layouts, the float property became very important. Float allows text and other content to flow around elements, and perhaps more importantly, floats allow you to create columns.

The float property accepts 4 values: left, right, none, and inherit. By default, float is set to none on all elements, and the most commonly used values are left and right.

Let’s say you had a div and you wanted to have some other paragraph text flow around it, like in a magazine. In your markup, you would first place the div and then place the paragraph text after it. The div shouldn’t go inside the paragraph. Next, you would need to apply an explicit width to your floated element, so that it doesn’t just span across its container. Finally you should apply the float property to the div and set the value to left. This will send the div over to the left of the container, and the text will appear to flow around it. It’s a good idea to add some padding as well, because for the sake of readability, you almost never want text to run right up against another element.

Columns

Nearly every modern CSS framework creates columns using floats. Here’s how you can create some simple columns on your own.

Creating columns is simpler than you might think. To create columns, you’ll need at least 3 divs. The first div will act as a container, and the second two divs will go inside the container. For our purposes, we’ll name the two child divs column 1 and column 2.

We’ll set an explicit width on each one of the columns, and then tell the columns to float to the left. We can also create some gutters between the columns by adding some margin to the right side.

If you want your columns to fill the entire width of the page, you’ll need to do your math carefully. If the width, margin, padding, and borders on the columns all combine to a pixel value that is wider than the parent container, the columns will appear to stack, rather than appearing side by side one another.

Finally, if you intentionally want an element to appear below a floated element, like in the case of a footer for example, apply the clear property to it and set its value to “both.”

Fixing Floats

From the previous examples, and from your own experience, you may have noticed that floats don’t always behave quite like you’d expect. In particular, the parent element will often appear to be collapsed. There are a couple ways to fix this.

The best and easiest way to fix a collapsed parent, is to apply the overflow property and set the value to auto or hidden. This is the best fix in an ideal world, but unfortunately, this fix isn’t always possible in practice, as it does not work in Internet Explorer 6.

Another method is to float the parent element. This will allow it to expand to fix the child elements, but again, this isn’t always possible in practice, because it might have undesirable effects on your layout.

If the first two methods don’t work for your layout, there is one more outdated method that you can try, and that is to add extra markup. This method is most often implemented by adding a div at the bottom of the container, and setting its clear property to both. This isn’t recommended because it adds non-semantic markup, but it can solve the problem quickly and easily if nothing else seems to work.

Resources

Iterators

In javascript, there are a few different ways to loop through the members of an object, or the values in an array. Today we are going to look at the differences between them.

for;; loop

When working with arrays, you can use a for loop to access each item of your array. If you are familiar with C or similar languages, this should look familiar to you

var myArray = ["dog", "cat", "hamburger"];

for(var i = 0; i < myArray.length; i++) {
  var item = myArray[i];
  console.log(item);
}

We use the for keyword, and in parentheses we put three statements, separated by semicolons. In the first statement, we declare a variable that will hold our current iteration number throughout the loop. We call this i. You can use any name for this variable, but typically it is i, or if i is being used, j, and so on.

The next statement is a stop condition. When this condition evaluates to true, the loop will terminate; In this case, we make sure our i variable is less than the length of our array. Remember array indices start at zero, so if we have 3 elements in our array, the last element is at index 2;

The final statement is executed after each iteration of the loop. Here we increment i by one by using the plus-plus operator;

Inside of our loop, we can get the item at our current position by calling myArray sub - i; We can then do whatever we want to do with the elements in our array

for..in loop

If we want to get each property from a javascript object, we can use a different form of for loop, the for..in loop.

var person = {name: "Joe", age: 20, gender: 'M'};
var key;

for(key in person){
  var value = person[key];
  console.log(key + ' = ' + value)
}

Here, we declare a variable we will call key. In each loop of the iteration, key will hold the string name of one of the properties of our object;

We again use the keyword for, but this time we say ‘key in person’. This means we are going to take each property of person, and assign that name to key;

Then inside the loop we can again assign value to person sub key

If there are any properties declared on the prototype, they will also be iterated over, but sometimes you just want the properties of the object itself, and not the prototype.

function Person(name, age){
  this.name = name;
  this.age = age;
}
Person.prototype.species = 'Human';

var joe = new Person('Joe', 20);
var key;

for(key in joe){
  console.log(key);
  if(joe.hasOwnProperty(key))
    console.log(key, value)
}

In this example, each person object has a name and age, but also has species defined through the prototype; If we only wanted to loop over name and age, we can check if the person object has that property using hasOwnProperty. If it returns true, that key is defined on the object, not it’s prototype.

forEach

In future versions of JavaScript, a forEach method will be defined on Array. Some javascript libraries create their own versions of this for backwards compatibility, and you can quickly add some code to make it available in older javascript engines.

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}

Here we call the forEach method directly on the array and pass it a function. This function will be called for each value in the array with the first argument being the value, and the second being the iteration number;

var myArray = ["dog", "cat", "hamburger"];

myArray.forEach(function(item, i){
  console.log(item);
})

This can be a convenient way to loop through an array, but be aware that since it is using an inner function, if you wanted to return from your outer function from within the loop, you cannot because that return will be scoped to the inner function.