I created a javascript code to create grid and populate it with cards, using data from json file, and load them into a web page.
This is the code:
// load data into grid container
const container = document.querySelector(".grid");
// get data from the file, using loadData(), inside it populateContainer
function loadData() {
const request = new XMLHttpRequest();
request.open("get", "data.json");
request.onload = () => {
try {
const json = JSON.parse(request.responseText);
populateContainer(json);
} catch (e) {
console.warn("error");
}
};
request.send();
}
function populateContainer(json) {
while (container.firstChild) {
container.removeChild(container.firstChild);
}
json.forEach((row) => {
const card = document.createElement("div");
card.setAttribute("class", `grid-item ${row[7]}`);
card.setAttribute("data-category", `${row[7]}`);
// header
let header = document.createElement("div");
header.setAttribute("class", "card-header");
header.innerHTML = `Current = ${row[1]}$ Original Price = ${row[2]}$ / Discount = ${row[3]}%`;
card.appendChild(header);
// pic
let img = document.createElement("img");
img.setAttribute("class", "card-image");
img.src = `https://${row[6]}`;
card.appendChild(img);
// BODY
let cardBody = document.createElement("div");
cardBody.setAttribute("class", "card-content");
card.appendChild(cardBody);
// -->Title + link
let cardTitle = document.createElement("h4");
cardTitle.setAttribute("class", "card-title");
cardTitle.innerHTML = `<a href='https://${row[4]}'>${row[0]}</a>`;
cardBody.appendChild(cardTitle);
container.appendChild(card);
});
}
document.addEventListener("DOMContentLoaded", () => {
loadData();
});
This is the html body (the javascript script is in main.js
file):
<body>
<div id="filters" class=".filter-button-group button-group">
<div class="button All"><a href="#">show all</a></div>
<div class="button HomeGarden"><a href="#">Home & Garden</a></div>
<div class="button Electronics"><a href="#">Electronics</a></div>
<div class="button MomKids"><a href="#">Mom & Kids</a></div>
<div class="button SportsOutdoor"><a href="#">Sports & Outdoor</a></div>
<div class="button Accessories"><a href="#">Accessories</a></div>
<div class="button HealthBeauty"><a href="#">Health & Beauty</a></div>
</div>
<div class="grid">
</div>
<script src="main.js"></script>
</body>
The code work well, and it create the grid and elements inside it,
but when I want to add a filter for those cards by category, using library like https://listjs.com
or https://isotope.metafizzy.co
it doesnt work.
How I can apply the filter to my code ?
question from:
https://stackoverflow.com/questions/65858125/using-javascript-libraries-dont-work-on-webpage-when-loading-data-from-json-fil 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…