Project Part Chapter (1) - Using Filter Dataset
Project Part Chapter (1) - Using Filter Dataset
The dataset read-only property of the HTMLElement interface provides read/write access to custom data
attributes ( data-* ) on elements.
It exposes a map of strings ( DOMStringMap ) with an entry for each data-* attribute.
Note: The dataset property itself can be read, but not directly written.
Style.css
*{
margin: 0;
padding: 0;
box-sizing: border-box;
outline: none;
border: 0;
}
::-webkit-scrollbar {
width: 6px;
background-color: #333;
}
/* Handle */
::-webkit-scrollbar-thumb {
background: lightpink;
border-radius: 5px;
}
/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
background: palevioletred;
}
body {
background-color: #0d0909;
color: white;
}
.filter {
width: 1200px;
margin: auto;
margin-top: 3em;
}
button {
padding: 1em;
cursor: pointer;
}
.buttons {
margin-bottom: 2em;
}
.card {
width: 380px;
padding: 5em;
}
.shoe {
background-color: darkgreen;
}
.shirt {
background-color: cadetblue;
}
.pant {
background-color: coral;
}
Script.js
function filterCards(e) {
cards.forEach(card => {
card.style.display = "block";
// console.log(card.dataset.info);
// console.log(e.target.dataset.btn);
const cardType = card.dataset.info;
const btnType = e.target.dataset.btn;
if (cardType !== btnType) {
card.style.display = "none"
}
})
}
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device -width, initial-scale=1.0">
<title>JavaScript Filter</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section class="filter">
<div class="buttons">
<button>All</button>
<button data-btn="shoe">Shoes</button>
<button data-btn="shirt">Shirts</button>
<button data-btn="pant">Pants</button>
</div>
<div class="cards">
<div class="card shoe" data-info="shoe">
<p>Shoe</p>
<p>$100</p>
</div>
<div class="card shirt" data-info="shirt">
<p>Shirt</p>
<p>$100</p>
</div>
<div class="card pant" data-info="pant">
<p>Pant</p>
<p>$100</p>
</div>
<div class="card shoe" data-info="shoe">
<p>Shoe</p>
<p>$100</p>
</div>
<div class="card shirt" data-info="shirt">
<p>Shirt</p>
<p>$100</p>
</div>
<div class="card pant" data-info="pant">
<p>Pant</p>
<p>$100</p>
</div>
<div class="card shoe" data-info="shoe">
<p>Shoe</p>
<p>$100</p>
</div>
<div class="card shirt" data-info="shirt">
<p>Shirt</p>
<p>$100</p>