Multiple Flickity galleries with custom navigation UI (vanilla JS)
I have initialized multiple galleries on a page like so and I'm now trying to make some sort of thumbnail navigation for each one of them. Basically it should be a grid of thumbnails, each of them clickable so that the associated slide in the connected gallery is selected. I've used your pen as a starting point but I somehow get stuck in the for loops and I wondered if you've tackled this task before?
Sure thing, see demo on CodePen
<!-- wrap gallery and navigation in a container element -->
<div class="gallery-container">
<div class="gallery">
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
</div>
<ol class="gallery-nav">
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
</ol>
</div>
// get all containers
var galleryContainers = document.querySelectorAll('.gallery-container');
for ( var i=0; i < galleryContainers.length; i++ ) {
initGalleryContainer( galleryContainers[i] );
}
// init flickity and thumbnail nav for container
function initGalleryContainer( container ) {
// init flickity
var galleryElem = container.querySelector('.gallery');
var flkty = new Flickity( galleryElem );
// hook up navigation
var nav = container.querySelector('.gallery-nav');
// get array of items, hack with slice.call so we can use .indexOf
var items = Array.prototype.slice.call( nav.children );
nav.addEventListener( 'click', function( event ) {
// only link clicks
if ( !matchesSelector( event.target, 'a' ) ) {
return;
}
event.preventDefault();
var item = event.target.parentNode;
var index = items.indexOf( item );
flkty.select( index );
});
}
Sweet, thanks! That worked! For some reason matchesSelector doesn't work on a tags for me, so I pointed it to the img within instead, which works fine.
Thanks @desandro, that's exactly what I was looking for! 👍
Would you guys have any idea why it doesn't work with a tags?
From my tests it works if the a tag doesn't have any children, but if there's any tags inside it doesn't work. Would you have any idea why?
Quick update:
If I add pointer-events: none; to all children elements of the a tag it works. Not a perfect solution, but can't think of anything else right now. Still researching it.
.gallery-nav a > * {
pointer-events: none;
}