Search code examples
fotorama

Fotorama - deep linking and browser history


I love the fact that Fotorama updates the URL with a hash specific to each slide, but when I use the browser back button the slideshow doesn't update to the previously viewed slide. Is there a way to have Fotorama record the deep linking in the browser history, so that using the browsers back/forward buttons update the slide show accordingly? Thanks


Solution

  • There is no built-in way to do that. Write your own solution, using 'fotorama:show' event and fotorama.show()method:

    <script>
      $(function () {
        window.onpopstate = function (e) {
          var hash = location.hash.replace(/^#/, '');
          if (fotorama && hash) {
            fotorama.show(hash);
          }
        };
    
        var fotorama = $('.fotorama')
            .on('fotorama:show', function (e, fotorama) {
              var hash = fotorama.activeFrame.id || fotorama.activeIndex;
              console.log('fotorama:show', hash);
              if (window.history && location.hash.replace(/^#/, '') != hash) {
                history.pushState(null, null, '#' + hash);
              }
            })
            .fotorama({
              startindex: location.hash.replace(/^#/, '')
            })
            .data('fotorama');
      });
    </script>
    
    <!-- Fotorama -->
    <div class="fotorama"
         data-auto="false">
      <a href="1.jpg"></a>
      <a href="2.jpg"></a>
      <a href="3.jpg" id="three"></a>
    </div>
    

    Attribute data-auto="false" is important!

    Demo: http://jsfiddle.net/artpolikarpov/2Enwa/show/

    Original fiddle: http://jsfiddle.net/artpolikarpov/2Enwa/ (not working because of iframe)