Victor
Victor

Reputation: 489

List of links split into columns

I'm fetching links with an ajax call and the content is dynamic.

I want to make the links flow: top to bottom for 10 links and into a new column for an other 10 links etc..

I need something that would look like this: http://jsfiddle.net/89JKM/18/, but that would work cross-browser. Also if the number or links was for example 15 then the first columns of 10 should fill up before it fills up the second colums with 5 and leave the last column empty. I believe that a jQuery script would do the trick or if there is some cool CSS-magic.

Upvotes: 1

Views: 353

Answers (1)

David Thomas
David Thomas

Reputation: 253318

Well, here's one approach:

function cssSupportFor(prop) {
    if (!prop) {
        // you have to supply a property to test
        return false;
    }
    else {
        var styles = document.body.style;

        // testing for native support:
        if (prop in styles) {
            // returns the property
            return prop;
        }
        else {
            // tests for vendor-prefixed support:
            var vendors = ['Moz', 'Webkit', 'Ms', 'O'],
                // upper-cases the first letter of the property for camel-casing
                Prop = prop[0].toUpperCase() + prop.substring(1);
            for (var i = 0, len = vendors.length; i < len; i++) {
                if ((vendors[i] + Prop) in styles) {
                    // returns the vendor-prefixed property
                    return vendors[i] + Prop;
                }
                else if (i == (vendors.length - 1)) {
                    // if no vendor-prefixed support, or native support, returns false
                    return false;
                }
            }
        }
    }
}

// if there's support for the tested property then it's implemented here
if (cssSupportFor('columnCount')) {
    var prop = cssSupportFor('columnCount');
    $('#linklist')[0].style[prop] = 3;
}
// otherwise the following jQuery kicks in to achieve much the same
else {
    var aElems = $('#linklist a'),
        cols = Math.ceil(aElems.length / 10);

    for (var i = 0, len = cols; i < cols; i++) {
        var d = $('<div />', {
            'class': 'col'
        }).appendTo('#linklist');
        $('#linklist > a:lt(10)').appendTo(d);
    }
}​

JS Fiddle demo.

References:

Upvotes: 2

Related Questions