0
\$\begingroup\$

I have a grid that lists products. The grid is three columns wide, but it could grow to be four or five columns wide. I've written my script to count the columns. The markup is something like this:

<ul>
 <li class="item first">...</li>
 <li class="item">...</li>
 <li class="item">...</li>
 <li class="item first">...</li>
 <li class="item">...</li>
 <li class="item">...</li>
</ul>

In the project, I can't change the markup. I can however write JavaScript/jQuery any which way I please. What I have is working, but I'm using four loops. Since my JS chops aren't too hot, I'm not convinced that what I have is particularly fast or concise.

jQuery(document).ready(function ($) {
"use strict";
var maxItemHeight,
 firstItem = $('.item.first'),
 gridRow = [],
 i;
firstItem.each(function () {
 gridRow.length = 0;
 maxItemHeight = 0;
 gridRow.push($(this));
 $(this).nextUntil(firstItem).each(function () {
 gridRow.push($(this));
 });
 for (i = 0; i < gridRow.length; i++) {
 maxItemHeight = (gridRow[i].find('h2').outerHeight() > maxItemHeight) ? gridRow[i].find('h2').outerHeight() : maxItemHeight;
 };
 for (i = 0; i < gridRow.length; i++) {
 gridRow[i].find('h2').css('height', maxItemHeight);
 }; 
});
});

How could this be improved?

asked Jul 9, 2012 at 9:18
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Can't say if this is much faster, but it's more concise

jQuery(document).ready(function($) {
 "use strict";
 var firstItems = $('.item.first');
 firstItems.each(function() {
 var $first, row, headings, heights, maxHeight;
 $first = $(this);
 // Get collection of "columns"
 row = $first.add($first.nextUntil(firstItems));
 // Find each column's heading
 headings = row.find("h2"); 
 // Get the heights of the headings
 heights = headings.map(function () {
 return $(this).outerHeight();
 }).toArray();
 // Get the maximum
 maxHeight = Math.max.apply(null, heights);
 // Set the heading heights to the maximum
 headings.css("height", maxHeight);
 });
});​​​

--Edit--

In my particular instance, the above script had conflict issues with prototype, since it lives inside a Magento install. I sought help and found this improvement.

/Jezen

answered Jul 9, 2012 at 12:16
\$\endgroup\$
2
  • \$\begingroup\$ That is so damn cool. I feel there's plenty to learn from this. Thanks! \$\endgroup\$ Commented Jul 9, 2012 at 13:12
  • \$\begingroup\$ I'm editing in a fix. \$\endgroup\$ Commented Jul 11, 2012 at 15:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.