user3350511 user3350511 - 4 months ago 16
Javascript Question

Displaying posts in three columns?

These few lines display my WordPress posts in two columns. Is it possible to change it to three columns?

if ($(window).width() > 600) {
var i = 0,
colOne = new Array(),
colTwo = new Array();
jQuery('#cff .cff-item').each(function() {
i++;
var $self = jQuery(this);

function isEven(value) {
if (value % 2 == 0)
return true;
else
return false;
}
if (isEven(i)) {
colTwo.push($self);
} else {
colOne.push($self);
}
$self.remove();
});
$('#cff').prepend('<div class="col-one" style="width: 45%; float: left; margin: 0 2.5%;"></div><div class="col-two" style="width: 45%; float: left; margin: 0 2.5%;"></div>');
for (var i = 0; i < colOne.length; i++) {
jQuery('#cff .col-one').append(colOne[i]);
};
for (var i = 0; i < colOne.length; i++) {
jQuery('#cff .col-two').append(colTwo[i]);
};
}


How would I do it?

Answer

Answering your question directly, yes, you can easily edit this code such that it now works with three columns:

if ($(window).width() > 600) {
    var columnsCount = 3;
    var $columns = new Array(columnsCount);

    // Create columns
    for (var i = 0; i < columnsCount; i++) {
      $columns[i] = $("<div class='col' style='float: left; margin: 0;'/>")
        .css({
          "width": Math.floor(45 / columnsCount).toFixed(2) + "%",
          "margin-left": Math.floor(5.0 / columnsCount).toFixed(2) + "%",
          "margin-right": Math.floor(5.0 / columnsCount).toFixed(2) + "%"
        });
    }  

    // Relocate items
    $("#cff .cff-item").each(function (i) {
        $(this).appendTo($columns[i]);
    });

    // Replace grid
    $("#cff").empty();
    $columns.forEach(function($c) { $("#cff").append($c); });
}

However, as I said before, it is much a better idea to achieve this using CSS.
Something like would solve all your problems:

  .cff-item {
    display: inline-block;
    width: 90%;
    margin: 0 5%;
  }

@media (min-width: 600px) {
  .cff-item {
    width: 45%;
    margin: 0 2.5%;
  }
}