0

I'm trying to make a script to put the elements inside a container into columns. The script works fine until I get to 4 column. I can't see where I'm going wrong. Here's the code, and the demo

var container = '.bar',
    children = $(container).children().length,
    column = 4,
    width = $(container).width() / column - 20;

function columnizer(value) {

    var i = 1,
        x = Math.ceil(value / column),
        z = Math.round(value / column),
        y = '<div class="column" />';

    $(container).children().slice(0, x).wrapAll(y);

    while (i < column) {
        if (value % 2 === 0 && z === 1 ) {
            $(container).children().slice(i, x * i).wrapAll(y);
            i++;
        }
        else if (value % 2 === 0 && z > 1) {                
            $(container).children().slice(i, x + i * i).wrapAll(y);
            i++;            
        }
        else {
            $(container).children().slice(i, x + i).wrapAll(y);
            i++;
        }
    }
}
1
  • 1
    maybe if you stop naming variables x, y and z the problem could pop out easier Commented Nov 13, 2011 at 2:19

1 Answer 1

2
$(function() {

var container = '.bar',
    children = $(container).children().length,
    column = 4,
    width = $(container).width() / column - 20;

function columnizer(value) {
    var i = 0,
        x = Math.ceil(value / column),
        z = Math.round(value / column),
                y = '<div class="column" />';

    while (i < column ) {   
        $(container).children(':not("div.column")').slice(0, x).wrapAll(y);
        i++;
        }
}

columnizer(children);

$(container).append("<div class='clear'></div>");

$('.column').width(width);

});

Also, change your test data to include a number after every Lorum or Duis. Otherwise, the code may look like its working but really not be.

This technique also works for any number of columns (rather than just 4 columns).

Sign up to request clarification or add additional context in comments.

1 Comment

I guess I was making it too complicated for myself. Thanks for the help.

Your Answer

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.