Category Filter
Home
Snippets
Category Filter
HTML
CSS
JS
<div class="filter-buttons"> <button data-category="all" class="active">All</button> <button data-category="fruits">Fruits</button> <button data-category="vegetables">Vegetables</button> <button data-category="dairy">Dairy</button> </div> <div class="items"> <div class="item" data-category="fruits">Apple</div> <div class="item" data-category="fruits">Banana</div> <div class="item" data-category="vegetables">Carrot</div> <div class="item" data-category="vegetables">Broccoli</div> <div class="item" data-category="dairy">Milk</div> <div class="item" data-category="dairy">Cheese</div> </div>
body { font-family: Arial, sans-serif; display: flex; flex-direction: column; align-items: center; margin: 0; padding: 20px; background-color: #f9f9f9; } .filter-buttons { margin-bottom: 20px; } .filter-buttons button { padding: 10px 15px; margin: 0 5px; border: none; background-color: #007BFF; color: white; border-radius: 5px; cursor: pointer; transition: background-color 0.3s ease; } .filter-buttons button:hover { background-color: #0056b3; } .filter-buttons button.active { background-color: #0056b3; } .items { display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; } .item { width: 100px; padding: 10px; border: 1px solid #ddd; border-radius: 5px; text-align: center; background-color: #fff; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .hidden { display: none; }
const buttons = document.querySelectorAll('.filter-buttons button'); const items = document.querySelectorAll('.item'); buttons.forEach(button => { button.addEventListener('click', () => { buttons.forEach(btn => btn.classList.remove('active')); button.classList.add('active'); const category = button.getAttribute('data-category'); items.forEach(item => { if (category === 'all' || item.getAttribute('data-category') === category) { item.classList.remove('hidden'); } else { item.classList.add('hidden'); } }); }); });
Ad #1
Ad #2
Scroll to Top