I'm looking to display images dynamically and according to their category. I have 4 buttons with the 1st I would like to display all the images and the 3 others I would like to sort them according to their categories. To know that an image can be in several categories.
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div class="link">
<a onclick="showImg()" class="link__color">All</a><!--category: 0-->
<a onclick="showImg()" class="link__color">category-1</a>
<a onclick="showImg()" class="link__color">category-2</a>
<a onclick="showImg()" class="link__color">category-3</a>
</div>
<div class="container">
<!-- <div class="container__img"><img class="img" src=""></div> -->
</div>
</body>
</html>
JS:
const partners = [
{img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTP267XEMpkNGK6SFQ97S0H417cdi3wwu6PtweMTOGSPreaJqFJWQ'`, category: [0,1,3]},
{img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR8YvxkmxhzlS3EQ9nmwODbfDvxzdYZZCbBl_Q3mkw53qH8QIv0hQ'`, category: [0,2]},
{img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQGV9LR9tr0hSWJdUcD15OSk7p3X47sy4QFBB6SLOQXQYt7G8AnfA'`, category: [0,1,2]},
{img: `src='https://c1.staticflickr.com/4/3823/11294769684_5d4b0d1a23_n.jpg'`, category: [0,1,2]},
{img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnccHtrN6iwkll-kIreBtv9jTM831XY2-wRvtevpb8ApCtdC27'`, category: [0,2,3]},
{img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnccHtrN6iwkll-kIreBtv9jTM831XY2-wRvtevpb8ApCtdC27'`, category: [0,2]},
{img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSUgwZXDhsiXxNBQ8KAxFvVcOGU0mMd8gohhRf5OP4z0NOjeO6N'`, category: [0,3]},
];
function showImg(category) {
const createDiv = document.createElement('div').setAttribute('class', 'container__img');
/* creatDiv = is the div that will surround every img */
partners.forEach(function() {
if() {
}
});
}
That's where I am after trying a lot of things. So I would like to have each image put it in my class: container__img. And I'm not sure that forEach () is the right idea. (Plunker: https://plnkr.co/edit/OqCFuDExAbae8KDkfAhI?p=preview)
think it's not very complicated but for the moment I can't think of any ideas.
{img: src="..."}?forEachis the preferred way to visit each element in an array. I would usefilter, before theforEach, instead of theif, for readability reasons..filter(image => image.category.includes(category)) .forEach(image => {...})data-src, then visit them in JavaScript byelement.dataset.src.