Home > Back-end >  Keep active class on gallery navigation when using pagination
Keep active class on gallery navigation when using pagination

Time:10-17

I have the following navigation on the gallery page of my website that allows users to filter the images by category.

<ul>
  <li><a href="/gallery/" class="active">All</a></li>
  <li><a href="/gallery/our-gym/">Our Gym</a></li>
  <li><a href="/gallery/our-classes/">Our Classes</a></li>
  <li><a href="/gallery/our-coaches/">Our Coaches</a></li>
</ul>

I've added the following snippet to add the class 'active' the category that is currently being viewed by the user.

<script>
  jQuery(function($) {
    var path = window.location.href;
    $('.gallery_listing_wrapper li a').each(function() {
      if (this.href === path) {
        $(this).addClass('active');
      }
    });
});
</script>

This works for the above gallery navigation however once I navigate using the pagination it doesn't work.

The URL for the pagination is slightly different to the gallery and its categories.

For example - instead of /gallery/our-gym/ - page/ and the page number is added to the URL i.e. /gallery/page/2/

Is it possible to adjust the above snippet to keep the active class on All when the pagination is being used?

CodePudding user response:

You could always just add the class to the "All" button if none of the other buttons match the current URL.

<script>
  jQuery(function($) {
    var path = window.location.href;
    let match = $(`.gallery_listing_wrapper li a[href="${path}"]`);
    if(match.length >= 1)
      match.addClass("active");
    else
      $(".gallery_listing_wrapper li a[href='/gallery/']").addClass("active");
  });
</script>
  • Related