views:

65

answers:

3

Example page: http://vincent-massaro.com/columns/columns.html

On this page, there are two ordered lists, one with four items, and one with eight. I need to write a condition that checks how many list items are in each ordered list, and if it's more than four, split them into columns; if there are less than four, don't split into columns. The code that accomplishes this now is:

$('.mcol', this).makeacolumnlists({cols: 3, colWidth: 0, equalHeight: 'ul', startN: 1});

Thanks in advance!

+1  A: 

check the number of li's using $('li').size()

Squirkle
I'm a jQuery newbie and wrote something using .length but it didn't work. I wasn't able to get it to check each li set individually.
This will give you the *total* number of `<li>` elements on the page.
patrick dw
$('.mcol').each.length; is a start - but how do I set it to check the number for each OL?
@user - See my answer. I updated it to use `<ol>` instead of `<ul>`.
patrick dw
You're right--I was just pointing out the `.size()` method. You do need to iterate through each ol/ul to make this work per list (as you do in your example).
Squirkle
+1  A: 

If you want the length property of <li> elements under a <ol>, you need to get it separately for each <ol>.

$('ol').each(function() {
    $(this).children('li').length;  // Gives you the number of <li>
                                    //    elements for the current <ol>
});
patrick dw
+1  A: 

One nice way is with a custom selector. Something like this:

$.expr[':'].hasmorethan4li = function(obj){
  return $(obj).children('li').length > 4;
};

Lets you do this:

$('ol:hasmorethan4li').makeacolumnlists(....);


Updated: As per the OP's question from the comments, here's a version of the selector for lists with between 4 and 12 items:

$.expr[':'].hasbetween4and12li = function(obj){
  var len = $(obj).children('li').length; // so we only have to run this once
  return len >= 4 && len <= 12;
};
Ken Redler
I like this solution.
Squirkle
This works perfectly! Thanks!
How would I change the condition to say greater than 4 AND less than or equal to 12? This doesn't seem to work: return $(obj).children('li').length > 4
Check the length once: `var len = $(obj).children('li').length;`. Then do your more complex comparison: `return len > 4 `.
Ken Redler
http://vincent-massaro.com/columns/columns.htmlUsing this right now and I get "Error: obj is not defined". See example page for code.
This `var len = $(obj).children('li').length;` has to go *inside* each custom selector definition, right before the `return`. We're doing this so it's cached and not run multiple times with each use of a custom selector. I've updated the answer with an example.
Ken Redler
Perfect, thanks again.