I have a website built on WordPress with a couple of hundred posts. Each post contains up to 10 images. Infinite Scroll is used to load in more posts automatically. What I want is for the main page to be a page of image galleries; one per post.
Here is what I have:
First, I add the galleries in the post loop. I use the post ID to create a unique Galleria ID. I also use a second class name to pass the image ratio to the JS (sure there is a better way?):
<div id="galleria-1609" class="galleria 0.5">
<a href="img01-800x400.jpg" alt="Large Image" ><img src="thumb.png" /></a>
<a href="img02-800x400.jpg" alt="Large Image" ><img src="thumb.png" /></a>
</div>
...and then the javascript is added...
<script>
Galleria.run('#galleria-1609', {
thumbnails: 'numbers',
height: 0.5, /* ratio */
preload: 1
});
</script>
This works fine for the first set of Galleries but when infinite scroll loads more posts, the javascript is stripped. After some searching I found Infinite Scroll has a callback function with access to the Array of new elements.
So I tried this code in a function called from the infinite scroll callback:
function loadSliders(arrayOfNewElems) {
$(arrayOfNewElems).each(function( i ) {
var newGal = $(this).find('.galleria');
//extract ratio from 2nd class name:
var ratio = $(newGal).attr('class').split(' ')[1];
var thisID = '#'+ $(newGal).attr('id');
Galleria.run(thisID, {
thumbnails: 'numbers',
height: ratio,
preload: 1
});
});
}
This does load one more set of Galleries, but fails after with this error:
TypeError: $(...).attr(...) is undefined
Any ideas on why I am getting this error or better ways to achieve this?
Got it worked out. For anyone else stuck on a similar problem. This is what I ended up with:
HTML:
<div id="galleria-1609" class="galleria" data-ratio="0.5">
<a href="img01-800x400.jpg" alt="Large Image" ><img src="thumb.png" /></a>
<a href="img02-800x400.jpg" alt="Large Image" ><img src="thumb.png" /></a>
</div>
JS:
function loadSliders(arrayOfNewElems) {
$(arrayOfNewElems).each(function( i ) {
$(this).find('.galleria').each(function( j ) {
//var ratio = $(this).attr('class').split(' ')[1];
//improved method:
var ratio = $(this).data('ratio');
var thisID = '#'+ $(this).attr('id');
Galleria.run(thisID, {
thumbnails: 'numbers',
height: ratio,
preload: 1
});
});
});
}
Updated to show HTML5 data- attribute as described in my comment.