Monday, February 28, 2011

Wrapping Grids in HTML with jQuery

So I was looking for a quick way to make an interface that allows me to dynamically add or remove the same type of child item to a grid-like parent element, where you have a certain number of items per row and they wrap around automagically. Anyway, I came up with a fun little jQuery function to automate it. Here we go:


function gridize(parent,children_per_row) {
var i=0;
$(parent).children().each( function() {
$(this).css("float","left");
if(i++ % children_per_row == 0) {
$(this).css("clear","left");
} else {
$(this).css("clear","none");
}
}
);
}


To use it, just toss in the id of your parent div and call gridize each time you add or remove an element. I used the jQuery templates plugin for defining and adding children.

Here's some scaffolding to get it working. This part isn't tested since I modified it on the fly from my working code, so YMMV:


$.template( "child_template", 
"<div id=\"child_${id}\">\
Whatever you want.\
        <input type=\"button\" onclick=\"del_child(${id})\" value=\"X\">\
</div>");


var current_id = 0;


function add_child() {
$.tmpl("child_template", {id: current_id}).appendTo("#parent");


        current_id++;

update_grid();
}


function del_child(id) {
$("#child_" + id).remove();

update_grid();
}


function update_grid() {
        gridize("#parent",3);
}


And some HTML:

<h1>A grid of items</h1>
<div id="parent">
</div>
<div style="clear: both;">
<input type="button" value="Add Child" onclick="add_child()">
</div>

Have fun!

No comments:

Post a Comment