I need to have multiple Masonry grids per page. I'm generating the code with a wordpress loop, so every div container has the same class name.
Is there a way to call Masonry on all div containers with the same name?
html
<!--Masonry 1-->
<div class="print-slider">
<div class="print-slider-sizer"></div>
<div class="gutter-sizer"></div>
<div class="print-slider-item"></div>
<div class="print-slider-item"></div>
<div class="print-slider-item"></div>
<div class="print-slider-item"></div>
</div>
<!--Masonry 2-->
<div class="print-slider">
<div class="print-slider-sizer"></div>
<div class="gutter-sizer"></div>
<div class="print-slider-item"></div>
<div class="print-slider-item"></div>
<div class="print-slider-item"></div>
<div class="print-slider-item"></div>
</div>
JS
var grid = document.querySelector('.print-slider');
var msnry;
imagesLoaded( grid, function() {
// init Isotope after all images have loaded
msnry = new Masonry( grid, {
itemSelector: '.print-slider-item',
columnWidth: '.print-slider-sizer',
gutter: '.gutter-sizer',
percentPosition: true,
});
});
Here is a code pen for the problem:
http://codepen.io/anon/pen/OXBrPb
Thanks for your help!
With document.querySelector('.print-slider')
you only get the first html element that has the print-slider
class. That's why only the first masonry is initialized.
Below is your code adjusted a bit in order to catch all .print-slider
elements and init the masonries respectively. The difference is that I get the elements by class name and then loop through them. I used body
as the selector for the imagesLoaded
because I didn't have the whole html structure. I would suggest that you wrap the masonries in one div and use that one for checking whether the images are loaded. Or, even better, do the check for each masonry separately, before doing the initialization inside the foreach.
var elements = document.getElementsByClassName('print-slider');
var msnry;
imagesLoaded( document.querySelector('body'), function() {
// init Isotope after all images have loaded
var n = elements.length;
for(var i = 0; i < n; i++){
msnry = new Masonry( elements[i], {
itemSelector: '.print-slider-item',
columnWidth: '.print-slider-sizer',
gutter: '.gutter-sizer',
percentPosition: true,
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With