JavaScript filter function not working

Hi, I have this JS function which allows me to filter my projects for example when u press on all it shows u all my projects and when u press on apps it filters down my projects to only show apps etc.

Whenever I run my code with this function on my local device it works well, the same when I upload it to GitHub pages but whenever it’s published to netlify, it doesn’t work. And I’m still new to JS and I can’t figure out what the problem is.

I tried putting the function on its own file, I tried placing the script in the HTML document along with the projects, and whenever I use type=‘module’ on the file it doesn’t work. Can someone please help me figure out why the filter doesn’t work.

Website: Portfolios - my projects

GitHub repo, HTML: Thembi-Dibotelo/pages/portfolio.html at main · GovanDBT/Thembi-Dibotelo · GitHub

GitHub repo, JS: Thembi-Dibotelo/js/filter.js at main · GovanDBT/Thembi-Dibotelo · GitHub

@Govan This issue isn’t Netlify specific, you’ll see the same thing if you run npm run build locally, go into the dist folder then serve it with npx serve.

When clicking the buttons in your UI the error shown in the console is:

image

Those buttons are using the onclick attribute to try and trigger the function filterObjects:

Parcel will be stripping the function, so what you’re looking for would be along the lines of:

If you explicitly specify those functions on the window then Parcel won’t strip them.

So change your filter.js to something like:

/** function that allows us to filter projects */
window.filterObjects = function filterObjects(c) {
  var x, i;
  x = document.getElementsByClassName("card");
  if (c == "all") c = "";
  for (i = 0; i < x.length; i++) {
    removeClass(x[i], "show");
    if(x[i].className.indexOf(c) > -1) addClass(x[i], "show")
  }
}

window.addClass = function addClass(element, name){
  var i, arr1, arr2;
  arr1 = element.className.split(" ");
  arr2 = name.split(" ");
  for(i = 0; i < arr2.length; i++){
    if (arr1.indexOf(arr2[i]) == -1){
      element.className += " " + arr2[i];
    }
  }
}

window.removeClass = function removeClass(element, name ){
  var i, arr1, arr2;
  arr1 = element.className.split(" ");
  arr2 = name.split(" ");
  for(i = 0; i < arr2.length; i++){
    while (arr1.indexOf(arr2[i]) > -1) {
      arr1.splice(arr1.indexOf(arr2[i]), 1)
    }
  }
  element.className = arr1.join(" ");
}

window.filterObjects("all");

2 Likes

Thanks for the advice, I was able to get it working.