Wednesday, 28 October 2020

How do I access filters through external URL and highlight only active filter class in the menu?

My Isotope gallery, which you can see here uses the code below to update the URL hashes in the address bar depending on which class is selected. If you select class Mishmash, you will see https://thedivtagguy.com/#filter=.mishmash in the address bar. This part works well but if you try going to this Mishmash category url I showed you above, it only highlights the filter class and doesn't actually sort the grid.

EDIT: This seems to be working off and on.

Why is this not working, the code seems to be valid?

<script>
(function($) {
    

function getHashFilter() {
  var hash = location.hash;
  // get filter=filterName
  var matches = location.hash.match( /filter=([^&]+)/i );
  var hashFilter = matches && matches[1];
  return hashFilter && decodeURIComponent( hashFilter );
}
$( function() {

  var $grid = $('.isotope');

  // bind filter button click
  var $filters = $('#filters').on( 'click', 'li', function() {
    var filterAttr = $( this ).attr('data-filter');
    // set filter in hash
    location.hash = 'filter=' + encodeURIComponent( filterAttr );
  });

  var isIsotopeInit = false;

  function onHashchange() {
    var hashFilter = getHashFilter();
    if ( !hashFilter && isIsotopeInit ) {
      return;
    }
    isIsotopeInit = true;
    console.log(hashFilter);
    // filter isotope
    $grid.isotope({
      // itemSelector: '.selector.col-md-6.col-lg-4',
      filter: hashFilter
    });
    // set selected class on button
    if ( hashFilter ) {
      $filters.find('.active').removeClass('active');
      console.log($filters.find('.active'));
      $filters.find('[data-filter="' + hashFilter + '"]').addClass('active');
    }
  }

  $(window).on( 'hashchange', onHashchange );

  // trigger event handler to init Isotope
  onHashchange();
});
    
})( jQuery );

Secondly, I've tried adding these links to my main menu (so that the grid is navigable from the top and if the user is on other pages, it would redirect to home and just filter the grid) and I've entered the full URLs for each category as the links, so the main menu has item Mishmash which has the link https://thedivtagguy.com/#filter=.mishmash. As you can see in the image below, for some reason all of the links are active but it's useless navigating using them; only the URL in the address bar changes without actually filtering. Which part of the code is causing this to happen and how do I make the other links inactive?

UPDATE: Video clip of the problem available here

enter image description here



from How do I access filters through external URL and highlight only active filter class in the menu?

No comments:

Post a Comment