Skip to content
On this page

Hash

This built-in plugin provides hash-based navigation:

  • starts Fancybox on page load if a matching element for the url hash value is found;
  • updates URL hash when navigating through gallery items;
  • monitors URL hash changes and closes Fancybox if user is detected using back button in browser.

The gallery name is used by default for the URL hash, but it can be customized or even set individually for each gallery item.

TIP

Hash plugin works well with traditionally designed pages or SPAs that properly handle URL hash changes. If you run into issues, just disable this plugin.

Example how to disable this plugin:

js
const options = {
  Hash: false,
};

or

js
Fancybox.defaults.Hash = false;

Examples

Customization

Custom values are supported using the data-slug attribute, example:

html
<a
  href="https://lipsum.app/id/32/1600x1200"
  data-fancybox="gallery"
  data-slug="cat"
>
  <img src="https://lipsum.app/id/32/200x150" />
</a>

<a
  href="https://lipsum.app/id/22/1600x1200"
  data-fancybox="gallery"
  data-slug="dog"
>
  <img src="https://lipsum.app/id/22/200x150" />
</a>

<a
  href="https://lipsum.app/id/23/1600x1200"
  data-fancybox="gallery"
  data-slug="bird"
>
  <img src="https://lipsum.app/id/23/200x150" />
</a>

Using API

To set custom hash for programmatically opened galleries, use the slug option. Here's an example of how to implement full functionality that also monitors hash changes:

js
const gallery_items = [
  {
    src: "https://lipsum.app/id/32/1600x1200",
    thumb: "https://lipsum.app/id/32/200x150",
  },
  {
    src: "https://lipsum.app/id/22/1600x1200",
    thumb: "https://lipsum.app/id/22/200x150",
  },
  {
    src: "https://lipsum.app/id/23/1600x1200",
    thumb: "https://lipsum.app/id/23/200x150",
  },
];

const gallery_options = {
  slug: "gallery",
  startIndex: 0,
};

document
  .getElementById("trigger-fancybox")
  .addEventListener("click", function () {
    Fancybox.show(gallery_items, gallery_options);
  });

function startFancyboxFromUrl() {
  const HashPlugin = Fancybox.Plugins.Hash;

  if (HashPlugin && !Fancybox.getInstance()) {
    const { hash, slug, index } = HashPlugin.parseURL();

    if (hash && slug === gallery_options.slug) {
      gallery_options.startIndex = index - 1;

      Fancybox.show(gallery_items, gallery_options);
    }
  }
}

window.addEventListener("hashchange", startFancyboxFromUrl, false);

startFancyboxFromUrl();