I created a blog post with three categories: (Digital Marketing Category, Tips & Advice Category, Cryptocurrency Category)
What I want to do is filter it.
For example, if I want to see all articles in the Digital Marketing category, I will click this button to show all Digital Marketing categories and hide other categories.
This is my code sample. The problem is that my filter is not working. where is the problem?
I tried adding JavaScript to make it work, but still doesn't work. where is the problem?
document.addEventListener("DOMContentLoaded", () => { "use strict"; /** * Article Category Filter */ const filterButtons = document.querySelectorAll('.blog-filters button'); const articleCards = document.querySelectorAll('.article-card'); filterButtons.forEach(button => { button.addEventListener('click', () => { const selectedCategory = button.getAttribute('data-category'); articleCards.forEach(card => { const cardCategory = card.getAttribute('data-category'); if (selectedCategory === 'all' || selectedCategory === cardCategory) { card.style.display = 'block'; } else { card.style.display = 'none'; } }); }); }); }); // this line added by community
<section id="blog" class="blog"> <div class="row"> <div class="col-md-8"> <div class="posts-list"> <div class="row"> <div class="col-lg-6 col-md-6 d-md-flex article-card" data-category="digital-marketing-category"> Blog Card </div> <!-- Article Card --> <div class="col-lg-6 col-md-6 d-md-flex article-card" data-category="tips-and-advice-category"> Blog Card </div> <!-- Article Card --> <div class="col-lg-6 col-md-6 d-md-flex article-card" data-category="cryptocurrency-category"> Blog Card </div> <!-- Article Card --> </div> </div> </div> <div class="col-md-4"> <div class="sidebar"> <h3 class="sidebar-title">Article Categories</h3> <div class="blog-filters"> <button data-category="filter-all">All</button> <button data-category="digital-marketing-category">Digital Marketing</button> <button data-category="tips-and-advice-category">Tips & Advice</button> <button data-category="cryptocurrency-category">Cryptocurrency</button> </div> </div> </div> </div> </section>
In your code, you define the
data-category
attribute of the "Filter All" button asdata-category="filter-all"
. So when the "All" button is clicked, theselectedCategory
variable in the JavaScript code will be set to "filter-all".However, in the if statement that filters articles by category, the statement is compared to "all", which does not match "filter-all", so no articles will be displayed.
This is your corrected code:
Also, the JS you provided is missing
});
at the end, not sure if this is just you accidentally missing that line of thought :)