How to make simple tabs/accordion remember tabs when back button is used?

339 Views Asked by At

We have a basic responsive tabs to accordion setup like this:

// Based on: http://codepen.io/jacmaes/pen/miBKI

// initialise when dom is ready
$(document).ready(function() {

  // initialise if .accordion is on the page
  if ($('.accordion')[0]) {

    // desktop initialisation
    if ($(window).width() > 736) {
      $('.accordion-content:not(:first)').hide(); // hide all but first tab content on larger viewports
      $('.accordion-title:first-child').addClass('active'); // activate first tab

    } else { // mobile initialisation
      $('.accordion-content').hide(); // hide all content items on narrow viewports
    };


    // Click functions
    $('.accordion-title').on('click', function() {

      // desktop click
      if ($(window).width() > 736) {
        $('.accordion-content').hide(); // hide all content
        $(this).next().show().prev().addClass('active').siblings().removeClass('active');
        return false; // stop browser jumping when tabs clicked

        } else { // mobile click
          $(this).toggleClass('active').next().toggle();
          return false; // stop browser jumping when tabs clicked
      };
    });
  }
});

We also use Snipcart which adds #!/cart to the end of any url if the cart is activated. And when the cart is closed, it leaves behind #!/ on the URL.

How would we go about making the tabs work with the browser back button - and have them play nice with Snipcart?

0

There are 0 best solutions below