I'm fairly new to Javascript and am writing a piece of code to create a filtering system for a portfolio grid (a grid of work examples that filter by category when a button is selected).
While the code works just fine, I feel like the way I'm writing it is overly clunky. Can someone please let me know if there's a way I can streamline/improve this code block?
Any help would be much appreciated - thanks! :D
var gridItem = document.querySelectorAll('.grid div');
var featuredItem = document.querySelector('.featured');
var filterBtn = document.querySelectorAll('.filter-btn');
function getAttributes(event) {
event.preventDefault();
var thisValue = event.target.getAttribute('data-filter');
// Get grid item filter attributes
for (let a = 0; a < gridItem.length; a++) {
const gridFilterAttr = gridItem[a].getAttribute('data-filterType');
if (thisValue == gridFilterAttr) {
gridItem[a].classList.add('active')
gridItem[a].classList.remove('not-active')
} else if (thisValue == 'all') {
gridItem[a].className = 'active';
featuredItem.className = 'featured active'
} else {
gridItem[a].classList.remove('active')
gridItem[a].classList.add('not-active')
}
}
}
for (let b = 0; b < filterBtn.length; b++) {
filterBtn[b].addEventListener('click', getAttributes);
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Js Projects</title>
<link rel="stylesheet" href="/assets/css/app.css">
</head>
<div class="container">
<button data-filter="all" class="filter-btn">All</button>
<button data-filter="web" class="filter-btn">Web Project</button>
<button data-filter="app" class="filter-btn">App</button>
<button data-filter="ux" class="filter-btn">UX/UI</button>
<div class="grid">
<div class="featured" data-filterType="web">Featured Item</div>
<div data-filterType="web">Web item</div>
<div data-filterType="app">App item</div>
<div data-filterType="ux">UX item</div>
<div data-filterType="web">Web item</div>
<div data-filterType="ux">UX item</div>
<div data-filterType="app">App item</div>
</div>
</div>
<!-- Scripts -->
<script src="/assets/js/grid.js"></script>
</body>
</html>