Thursday, November 11, 2010

Altering CSS for every nth element of a class

I wanted to improve on my previous jquery fix to remove the left padding for the 4th floating div.widget on the Rabbit Software homepage. If I add more widgets, the rows won't align correctly unless I can remove the padding from every 4th one. Because of the fixed width template and fixed width of the widgets, there are always 3 widgets per row.

The index of widgets counts up from 0, so I needed to fix every child whose index is a multiple of 3.

My original solution looked like this, and only applied to the 4th widget:
$(".home_widgets .widget:eq(3)").css("margin-left", "0");

The improved version, good for however many widgets I might add:
 $(".home_widgets .widget").each(function(index){
        if(index % 3 == 0) {
   $(this).css("margin-left", "0");

My references were the jQuery .each() API, and the Web Developers Notes Javascript Tutorial on arithmetical operations; see Modulus. I was really pleased with myself for figuring that out.

This blog post is reposted from my technical/professional blog, dbwebwork.
Photo credit: Creative Commons by Winfried Bruenken. Source: Worldnews

No comments:

Post a Comment