You are here

Variable height liquid float galleries with JQuery and Prototype

On the IVRPA sites (among other sites), I am using floated divs to create a gallery 'table'.

One of the known caveats of the floated thumbnail gallery is that all the thumbnails need to have the same dimensions, otherwise the floats break (see demo below). Having the thumbnails all be the same dimensions is one, but what if you want to have a (user submittable) caption to go with the thumbnail? There's no good way to influence the vertical dimension of that caption (or title, description, etc). So here's what goes wrong:

Demo of floated divs with variable heights
In the demo, you will see a number of red thumbnail+description placeholders. They could have any content, hence the random-ish heights. Each gallery item is in its own div (with green padding for clarity). Depending on your window width some of the items will go to the next line. If you change the window width so only 6 gallery items fit in one row, you'll see what goes wrong; Instead of dropping to the left margin, item nr. 7 gets stuck behind item nr. 3 and the following items stack up on item 3. It gets even worse with item a, and a rather unsightly whitespace appears on the left side under the first row of items.

Scripting to the rescue!
Javascript, used wisely, is no longer a dirty word in webdesign, as long as it is unobtrusive. Depending on your religion (or what you have on your site already for other purposes), you use either JQuery or Prototype to fix your pesky problems. On the IVRPA sites, I use prototype (and sc.rip.t;ac?ulous) because Lightbox did a better job than Thickbox, but Drupal is going the JQuery way and I like its elegance. So, as an exercise, I created fixes using both frameworks:

  • demo of fixed float gallery using JQuery (script)
  • demo of fixed float gallery using Prototype (script)

I'm sure neither script is a very good example of how you'ld use either framework, but the fix works nicely in both cases; When the window is resized, each gallery item is first restored to its normal ('broken') state. As soon as the script seas that one of the items is not in the same row as the previous one, it makes sure this item goes all the way to the left margin by adding a 'clear:left' style. Next the script sets the heights of all the items in the previous row to the same value, and removes the 'clear:left' style.

So which framework is better? Let me just say that for this particular fix there's not much difference. In JQuery it feels more like working with an elegant framework (the powerful $() operator beats having to use $() or getElementsByClassName or getElementsByTagName etc), but I would have liked to be able to supply a range with the each syntax.

Topics: