metafizzy / isotope

:revolving_hearts: Filter & sort magical layouts
https://isotope.metafizzy.co
11.03k stars 1.42k forks source link

Error with vanilla JS code when jQuery loaded #1629

Closed rniswonger closed 1 year ago

rniswonger commented 1 year ago

I have a situation where I'm using Isotope with vanilla JS on a WordPress site that also has jQuery loaded. I'm attempting to get rid of jQuery entirely but unable to do so at this time. However, I'm future-proofing new code to exclude jQuery as a dependency.

In this situation, I'm encountering a problem when filtering items with a custom function.

My reduced test case is here. It is a modified version of the Metafizzy-provided "Isotope - filtering, vanilla JS". The code is unchanged between the two, the only difference is that I added the jQuery library to the page.

Simple class-based filters work but the filters that use a custom function - "number > 50" and "-ium" - throw an error. Investigating this, I found the filtering function is no longer passed a copy of the element.

Thank you!

thesublimeobject commented 1 year ago

@rniswonger — Thank you for the detailed description! That is strange; I feel like I have many times had jQuery coming in from a WP site and it didn't affect it, but at some point long ago I feel like I encountered this...nonetheless, I have a temporary fix for you!

// filter functions
var filterFns = {
  // show if number is greater than 50
  numberGreaterThan50: function(nothing, itemElem) {
    var number = itemElem.querySelector('.number').textContent;
    return parseInt( number, 10 ) > 50;
  },
  // show if name ends with -ium
  ium: function(nothing, itemElem) {
    var name = itemElem.querySelector('.name').textContent;
    return name.match( /ium$/ );
  }
};

If you look at what the function is feeding back, it's feeding two arguments instead of just one because that jQuery is included. (This actually does seem like a bug, but I need to double-check a few things). So until you can get rid of jQuery, you should be able to use the above ^^. I have just added nothing as the first argument, since it's returning 0 there every time as far as I can tell. The second argument, then, is the element you're looking for. I ran your Pen with this and it did work.

Let me know if you have any other questions?

rniswonger commented 1 year ago

Thank you so much! This does indeed fix the issue. I hadn't noticed the additional argument.

thesublimeobject commented 1 year ago

@rniswonger — Also, this thread exists, which I didn't notice until afterwards. So, here's another similar way to do it. It also provides some more context for the issue. https://github.com/metafizzy/isotope/issues/1542#issuecomment-921413783