After few days without posting because I was traveling back to france, today I will talk about one way to create a grid like Pinterest. There is many plugins to do that but most of them are really big and based on jquery so you need to load a lot of stuff just to use 10% of a library. So I decided to develop my own one just using directives in angular and this without jquery or alternative lib.
So first we will have to think about what we need.
to compute the width of the grid
to compute the height of the grid
to compute the number of elements per rows
to compute the positions of each elements
And my goal is to use it like that
<gridlist="my_list"> this is my element <!-- the display of my element --></grid>
So let’s create the template for this new directive.
<divresizeng-style='computePositions()'><divng-repeat='elem in list'></div></div>
For now, nothing really complicated, one container with a style computed and inside the ng-repeat with my list. You can see the resize directive I introduce in a previous article.
Here is the first part of the directive, we just define some functions to help a bit the computation, like the margin between each elements which can be gave as a parameter of the grid, the same for the width of elements then the full width and height of elements including margins, the number of elements by row and the width of the grid. Now we can create the computePositions function.
This function will compute the position for each elements and then return the style of the grid.
To keep it simple, this algorithm will create an array to store the bottom of each columns and add the position of the element to the smallest column (the one with the smallest bottom).
Now you just need to set your grid container in relative and your items as absolute and it’s done and because of the resize, everytime you will resize your window, all the positions will be recomputed to be sure to maximize the number of items in your container.