Can’t say i like the idea of orphaning all those arrays into garbage cleanup.
(All major browsers except IE, and Opera Mini.)
//Define number of columns.
const x = 3;
//Create cols, store for later use.
var cols = [];
for(i = 0; i < x; i++) {
var c = document.createElement("div");
c.className = "col";
document.body.appendChild(c);
cols.push(c);
}
//Move posts to cols.
document.querySelectorAll('.post').forEach((post,index) => { cols[index % x].appendChild(post); })
I must admit my head is a bit sketchy right now (A few festive whiskeys), but it is a standard pattern in functional programming as far as I am aware. Avoiding mutation.
Nice one, thanks! It’s certainly a more concise solution and I understand it better (probably as it’s closer to how I’d do it with PHP) so I’ll have a play.
Although css columns will create columns as necessary I believe that the criteria for the question was for the divs to run in a horizontal sequence. Css columns however will stack the divs in each column in a vertical order. e.g. column1 would be 1,2,3,4 and column 2 would be 5,6,7,8 and so on. Instead of column1 = divs 1,3,5,7 and column2 = divs 2,4,6,8 etc.
To have the div numbers going horizontal and then forming columns as they wrap will require the CSS Grid layout method using the proposed value of 'masonry’. Unfortunately that value is not implemented fully yet so we will have to wait a while before production use.
Of course this assumes that each div.post is a different height otherwise flex or grid could do it now if all posts were the same height (which I doubt is the case).
Yeah, they are indeed different heights and it’s a masonry-style layout we’re going for. Good point about the columns and as you say, CSS grid is probably the closest pure-CSS solution.
Changing the layout like this affects accessibility so we might need to look at setting the tab order too.
I see that now, though it did not come across in my initial read.
To me, this layout would give a different visual flow to the actual content flow. Varying heights along a row, arranged in columns, to me would suggest reading in a column flow, vertical direction (as per columns). But the actual document content would be in a row flow (line by line), horizontal direction.
How a person would visually read it, differs from how a bot/screen-reader would read it.
Though I think “masonry” scripts already exist, for things like galleries.