Usually the number of columns with the waterfall layout of Gridzy.js is flexible/responsive and can be adjusted with the desiredWidth
option. However, sometimes you may want to have a fixed number of columns for all screen sizes. So let’s do this today.
Start with usual integration
1. Upload the Gridzy files to your server and add them to your website (usually in the head section):
<link rel="stylesheet" href="gridzy/gridzy.min.css" />
<script src="gridzy/gridzy.min.js"></script>
2. Add the HTML code (anywhere in the body section):
<div class="gridzy" data-gridzy-layout="waterfall">
<img src="https://picsum.photos/190/190?1" alt="a random image" />
<img src="https://picsum.photos/190/190?2" alt="another random image" />
<img src="https://picsum.photos/190/190?3" alt="yet another random image" />
<img src="https://picsum.photos/190/190?4" alt="a random image again" />
<img src="https://picsum.photos/190/190?5" alt="a fifth random image" />
<img src="https://picsum.photos/190/190?6" alt="a random image" />
<img src="https://picsum.photos/190/190?7" alt="another random image" />
<img src="https://picsum.photos/190/190?8" alt="yet another random image" />
<img src="https://picsum.photos/190/190?9" alt="a random image again" />
<img src="https://picsum.photos/190/190?10" alt="one last random image" />
</div>
Because we need the columns layout, we set the configuration parameter data-gridzy-layout
to waterfall
.
Then add responsive configuration
To achieve our goal, we need to adjust the desiredWidth
option depending on the available width. Because usually the available width depends on the viewport size, we need to make the desiredWidth
option responsive.
Add the following directly before the closing </body>
:
<script>
document.addEventListener('DOMContentLoaded', function() {
/**
* first we get the gridzy instance
*/
var gridzyInstance = document.querySelector('.gridzy').gridzy;
function update() {
var columns = 3;
var width = gridzyInstance.element.offsetWidth;
var space = gridzyInstance.getOption('spaceBetween');
gridzyInstance.setOptions({
desiredWidth: Math.round(((width + space) / columns) - space)
});
}
window.addEventListener('resize', update);
update();
});
</script>
About in the middle of the code you can see var columns = 3;
. This defines the number of columns. So change it to your needs.
Attention: There was a bug in Gridzy.js 2.2.0 and earlier, that disturbs this technique. So please ensure that you use at least Gridzy.js version 2.2.1.
That’s it!
Of course you can also put the last code snippet into a JS file for example.
Have fun! ✌😊