Skip to main content
2 of 2
added 1 character in body
KIKO Software
  • 5.9k
  • 13
  • 23

In my comment I said that this would be a lot shorter if you used JQuery. Now I don't want to say that JQuery is better than plain Javascript. There may be a good reason to not use JQuery. But I do want to show what the code would look like in JQuery.

$(".filter-btn").click(function() {
  let type = $(this).data("filter");
  let filter = (type == "all") ? "*" : "[data-filterType='"+type+"']";
  $(".grid div").hide().filter(filter).show();  
});

As you can see, this is a lot less verbose. You can see a live demo here.

I think it goes too far to explain this JQuery code in detail. In broad terms it does this:

  1. Bind an event handler to the "click" JavaScript event of your buttons.
  2. Extract the filter type from the data attribute of the clicked button.
  3. Based on that it creates a filter variable that selects the grid items to be shown.
  4. First hide all grid items and then only show the filtered ones.

It is the last line that does all the work.

I intentionally didn't change the HTML so this works on the same HTML as you have now.

KIKO Software
  • 5.9k
  • 13
  • 23