Utilizing URL Hashes to Integrate Isotope Filtering: A Comprehensive Guide

(Even though Wordpress is mentioned, I believe this problem is not specific to Wordpress)

I am currently building my own website using Wordpress and the theme I'm using includes the Isotope by Metafizzy package. This package helps in filtering posts on the page with clickable links.

You can view the page here

I wanted to try something similar to mypoorbrain.com, where the content on the page is filtered using URL hashes. The benefit of this is that users can navigate directly to a filtered section even from another page by entering a URL like

http://www.mypoorbrain.com/#illustration
.

After reading through the Isotope documentation, I found a section about implementing URL hashes. Below is the code snippet I tried inserting before the closing <head> tag:

<script>
  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', 'button', 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;
      // filter isotope
      $grid.isotope({
        itemSelector: '.selector col-md-6 col-lg-4',
        filter: hashFilter
      });
      // set selected class on button
      if (hashFilter) {
        $filters.find('.is-checked').removeClass('is-checked');
        $filters.find('[data-filter="' + hashFilter + '"]').addClass('is-checked');
      }
    }

    $(window).on('hashchange', onHashchange);
    // trigger event handler to init Isotope
    onHashchange();
  });
</script>

However, this code doesn't seem to be working as expected.

I suspect the issue might be related to accurately selecting the div elements (both the links and the items being sorted). Based on my observation using inspect element, it seems like the code for selecting the entire grid items is .selector col-md-6 col-lg-4', and the code for finding the filter buttons (or links) is

var $filterButtonGroup = $('.m-filters');
. Despite this, the filtering process still remains ineffective.

What could I be missing here? How can I ensure that the filters show up as hash links in the address bar?

Answer №1

To arrive at the resolution, follow these steps:

  1. Include the class .isotope in the parent element (.row) as it is currently missing.
  2. Remove any inline style declarations conflicting with the expected styling by isotope.
  3. Update the event listener from click on a elements to $('#filters').on('click', 'li'.. since the data-filter is bound to the li elements.
  4. Eliminate the unnecessary itemSelector option when using $grid.isotope as filtering direct children is the default behavior. Also, note that .selector col-md-6 col-lg-4' is an invalid selector and should potentially be corrected to .selector.col-md-6.col-lg-4'.

All modifications have been consolidated into this commit: https://github.com/moshfeu/isotope.js/commit/62b9798871e9452ade26d6e2863699869b8cb612.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with sending $ajax via jQuery to C# code behind and it's not working as expected

I am encountering an unusual issue when using jQuery and AJAX to post to C#. 1) The main page is not recognizing the method I am requesting through jQuery. To address this problem, I added an if statement in the page load function. If a specific item is ...

Integrate ng-admin with ui-router for enhanced functionality

My AngularJS project (version 1.4.9) is built using ui-router and contains multiple states defined as follows: .state('overview', { url: '/overview', parent: 'dashboard', templateUrl: 'views/dashboard/overview.html ...

How about creating a fresh variable in Assemble or merging two comparison helpers together?

Is it possible to create a new variable within a partial in Assemble (assemble.io) or combine two comparison helpers? For example: {#is somevar "yes" || anothervar "no"} In my partial, I have HTML that should only display if one of two different variable ...

What is the best way to incorporate a jQuery progress bar into a slideshow gallery?

My friend and I are working on enhancing our jQuery slideshow by adding a progress bar to show when the gallery will switch to the next image. Here is the code for our slideshow that we have written so far. We would greatly appreciate any help or suggestio ...

What occurs when the update function returned by React.useState() is invoked?

Just recently, I delved into the world of React hooks and decided to implement a small feature using them. The feature enables hidden texts to be displayed when users click on hyperlinks. Although I managed to make the code work, it appears that there are ...

The Google pie chart legend with the position labeled is malfunctioning and not displaying properly

In my project, I have integrated Google Charts to display a pie chart as a tooltip within a column chart. However, I am facing an issue where using legend: { position: 'labeled' } in the pie-chart settings is causing the bars of the column chart ...

Determine the number of distinct property values within a JSON API response

Running on a Ruby on Rails backend, I have a JSON API that serves an array of objects with the following structure: { "title_slug": "16-gaijin-games-bittrip-beat-linux-tar-gz", "platform": "Linux", "format": ".tar.gz", "title": "BIT.TRIP BEAT", ...

What are the steps to create a dynamic dropdown effect for navbar content using animations similar to transitions?

IMPORTANT: THE NAVIGATION BAR IS NOT USING BOOTSTRAP When I hover over the "More" button, the dropdown content appears suddenly and disappears abruptly when moving the mouse away. I would like to add a transition effect to make the dropdown content appear ...

The hamburger menu is not functioning properly online, but it works perfectly in xampp/localhost

I'm currently facing a challenge with my responsive menu. It works perfectly on my offline server in mobile format, but as soon as I upload it to the real server, it stops working. I've been grappling with this problem for hours. Here's the ...

adjusting state with React hooks

I currently have two buttons labeled create signature and Create delivery in my file PageOne.tsx. When the state is set to InDelivery, both buttons are visible. My goal is to hide the Create delivery button initially. However, when a user clicks on the cr ...

Guide on assigning a value to an input field using Vuejs

<div class="col-md-8"> <va-input label="Address 1" v-model="Address1" id="address" class="inp"> </va-input> </div> After calling the API to retrieve data, I need to populate the above input field wit ...

modify the controller variable and incorporate it into the view using a directive in Angular 1.5

I need to update a controller variable from a child directive, but even after updating the controller variable, the value doesn't change in the view. Should I use $scope.$apply() or $digest? Here is my code: http://plnkr.co/edit/zTKzofwjPfg9eXmgmi8s? ...

Extracting data using Ajax: Retrieving plain text content using getElementByTagName

I'm trying to scrape a specific piece of information from a URL using Ajax/jQuery. However, I'm still new to this and unsure of the correct syntax. Here is my current ajax call: $.ajax({ url: URL, dataType: 'text', success ...

Ensuring an image fits perfectly within a div that spans 100% width using CSS

I'm brand new to CSS and could use some guidance Here's the issue: I have a 1600 pixel wide image and a div that is 100% wide. Is there a method to adjust the image so it fits within the div, eliminating any horizontal scroll bars and cutting o ...

Node.js continues to multiply the data being sent to SQL with each AJAX post request

I'm currently learning how to interact with a database using node.js on the backend and jQuery ajax on the client side. Initially, I was able to get the basic post function to work when a user submits data for the first time. However, subsequent subm ...

How to position two rectangles below a header section

Although I am new to WordPress, I am looking to add two rectangles below the header on my page, with each rectangle linking to another page. Can someone guide me on how to achieve this? What tools or methods should I utilize for this task? ...

Ways to maximize the usefulness of input[type=number] for obtaining authentic value

When using input[type=number], I noticed that Chrome allows users to type not only numbers, but also special characters like the minus sign (-) for negative numbers. Surprisingly, it even permits multiple instances of these characters, such as ".....---888 ...

Showing off the latest products at the top of the list

Typically, when utilizing ngFor, the most recent item is displayed underneath the initial element. For instance, a list containing: [Apple, Orange, Banana] If we use ngFor to display this list: Apple Orange Banana I am interested in learning a method t ...

The dynamically generated hyperlink is not displaying correctly

I've been attempting to display a link on my page, but instead of returning the /register path, it immediately redirects to the UTMs.... The href displayed on the site is domain.com/?utm_campaign... rather than domain.com/register?utm_campaign... ...

Issue with toggling functionality on Material UI check boxes when they are printed in a loop

I am attempting to display checkboxes in rows of 4 dynamically, where the number of rows and checkbox values can vary. Below is my JSX code: matrix.map((row, index) => ( <TableRow key={index}> <TableCell al ...