I'm pretty beginner with jQuery, but I wanted to divide
<div>s up into columns without using a plugin. So far, I have a
<div> with an ID of
#columns and a bunch of
<div>s inside with the class
$('#columns').append('<div class="column first"></div>', '<div class="column mid"></div>', '<div class="column last"></div>'); $('#columns .proj-wrapper:nth-child(3n+1)').appendTo('.column.first'); $('#columns .proj-wrapper:nth-child(3n+2)').appendTo('.column.mid'); $('#columns .proj-wrapper:nth-child(3n+3)').appendTo('.column.last');
Basically I want to add all of the
div.proj-wrapper's into a column from left to right.
- I need 1, 4, 7, 10, etc. in the first column
- I need 2, 5, 8, 11, etc. in the mid column
- I need 3, 6, 9, 12, etc. in the last column
I think I know why this isn't working properly -- As it is, once the first
appendTo fires it changes the order of the
div.proj-wrapper's. I think I need to get them all to fire at the same time.
If anyone could help me figure out how to get all 3 of those
appendTo's to fire at the same time, I'd really appreciate it.
They can't be fired at the same time, but you can store the values for use later and the manipulation of the DOM won't matter.
Here's an example for you, but the gist of it is, store each of the queries as you go along into variables, and that will store the proper elements you will be inserting and in the proper order. From there, you can call your
appendTo's and it will always have the right variables to go off of.
// Create all three columns var first = $('<div/>').addClass('column').addClass('first'); var mid = $('<div/>').addClass('column').addClass('mid'); var last = $('<div/>').addClass('column').addClass('last'); // Store elements into variables for safe-keeping var fElems = $('#columns div:nth-child(3n+1)'); var mElems = $('#columns div:nth-child(3n+2)'); var lElems = $('#columns div:nth-child(3n+3)'); // Perform appends fElems.appendTo(first); mElems.appendTo(mid); lElems.appendTo(last); // Now append the columns to the element $('#columns').append(first,mid,last);