<div id="buttons"></div>
<div id="gallery">
<img src="https://wallpapercave.com/wp/wp3003567.jpg" data-tags="Ironman, Marvel" alt="Ironman">
<img src="https://images8.alphacoders.com/282/thumb-1920-282535.jpg" data-tags="Ironman, Marvel" alt="Ironman">
<img src="https://joyofapple.com/wp-content/uploads/2018/09/Batman-Featured.png" data-tags="Batman, DC" alt="Batman">
<img src="https://wallpapercave.com/wp/wp3533547.jpg" data-tags="Ironman, Marvel" alt="Ironman">
<img src="https://images2.alphacoders.com/707/thumb-1920-707960.png" data-tags="Flash, DC" alt="Flash">
<img src="https://wallpapercave.com/wp/wp1829308.jpg" data-tags="Flash, DC" alt="Flash">
<img src="https://wallup.net/wp-content/uploads/2016/01/188435-Batman.jpg" data-tags="Batman, DC" alt="Batman">
<img src="https://wallpaperplay.com/walls/full/8/0/8/201288.jpg" data-tags="Superman, DC" alt="Superman">
<img src="https://i.ytimg.com/vi/I7dhMa5f6BA/maxresdefault.jpg" data-tags="Batman, DC" alt="Batman">
<img src="https://wallpapercave.com/wp/wp2028630.jpg" data-tags="Dr.Strange, Marvel" alt="Dr.Strange">
</div>
#gallery {
margin-top: 20px;
img {
width: 150px;
height: 150px;
object-fit: cover;
}
}
button {
margin-right: 10px;
padding: 4px 10px;
border: none;
cursor: pointer;
font-size: 14px;
&.active {
background: white;
color: black;
border: 1px solid black;
}
}
View Compiled
(function () {
var $imgs = $('#gallery img');
var $buttons = $('#buttons');
var tagged = {};
$imgs.each(function () {
var img = this;
var tags = $(this).data('tags');
if (tags) {
tags.split(',').forEach(function (tagName) {
if (tagged[tagName] == null) {
tagged[tagName] = []
}
tagged[tagName].push(img);
})
}
})
$('<button />', {
text: 'Show All',
class: 'active',
click: function () {
$(this)
.addClass('active')
.siblings()
.removeClass('active');
$imgs.show();
}
}).appendTo($buttons);
$.each(tagged, function (tagName) {
$('<button/>', {
text: tagName + ' (' + tagged[tagName].length + ')',
click: function() {
$(this)
.addClass('active')
.siblings()
.removeClass('active');
$imgs
.hide()
.filter(tagged[tagName])
.show();
}
}).appendTo($buttons);
})
}());
This Pen doesn't use any external CSS resources.