Link a Filtered Gridzy.js Gallery Group

Since version 2 Gridzy.js have a very flexible and easy to use filter system. So you can always show only relevant pictures. Sometimes you may want to provide a direct URL to a filtered gallery. So let’s add such a feature.


Set Up your Gallery

First we need to set up the gallery as described in the filters section of the documentation.

Add Direct Link Feature

Afterwards we need to add the following code snippet directly before the closing </body> . (You could also put it into a Javascript file of course. Just consider to place it anywhere after the main Gridzy.js file.)

<script>
document.addEventListener("DOMContentLoaded", function(event) {
	var gridzyElement = document.querySelector('.gridzy'), gridzyInstance, changedHandler;
	if (gridzyElement && gridzyElement.gridzy) {
		gridzyInstance = gridzyElement.gridzy;
		changedHandler = gridzyInstance.getOption('onOptionsChanged');

		function update() {
			var filter = decodeURIComponent((location.hash).replace(/^#/, '').replace(/\&.*$/, '') || '');
			if (filter && filter !== gridzyInstance.getOption('filter')) {
				gridzyInstance.setOptions({
					filter: filter
				});
			}
		}
		window.addEventListener('hashchange', update);
		update();

		gridzyInstance.setOptions({
			onOptionsChanged: function(gridzy) {
				var filter = gridzy.getOption('filter');
				var hash = '#' + filter && filter !== '*' ? encodeURIComponent(filter) + (location.hash).replace(/^[^&]*(&.*)?$/, '$1') : '';
				if (location.hash !== hash) {
					location.hash = hash;
				}
				changedHandler(gridzy);
			}
		});
	}
});
</script>

That’s it!

As soon as you set a filter, you’ll see the specific URL in the browser address bar.


If there are multiple galleries on your page, the script only considers the most upper one. If you want to use it for an other gallery, please change the CSS selector .gridzy in the third line to a specific id like #myGallery for example, and add the id to the HTML main element of the specific gallery. For logical reasons it can’t be used for multiple galleries at the same time.

Happy linking ✌?

Updates:

March 16, 2019:
Optimized compatibility to PhotoSwipe

Be the first to leave a reply …

or

You can post as a guest if you like. But please consider, that I always review such comments before I switch them public, to prevent spam. If you want to see your comment public immediately, just sign up and in. It's just a click away and it's really simple. You don't even need a password. 😉