Reputation: 401
I have an HTML code with more section like this:
<section class="grid-1">
<div class="item-2">
<div class="item-6">
<img src="../img/image1.png" onclick="openModal();currentSlide(4)" class="hover-shadow cursor" style="display: none;">
</div>
<div class="item-6">
<img id="currentPhoto" src="../img/image2.png" onclick="openModal();currentSlide(5)" class="hover-shadow cursor" style="display: none;">
</div>
<div class="item-6">
<img id="currentPhoto" src="../img/image3.png" onclick="openModal();currentSlide(6)" class="hover-shadow cursor" style="display: none;">
</div>
</div>
</section>
the style="display: none;" has been added from this code:
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelectorAll('img').forEach(function(img){
img.onerror = function(){this.style.display='none';};
})
});
but is it possible to hide all the section class grid-1 if all the images sources are not available?
Upvotes: 1
Views: 85
Reputation: 728
You could add a class to the not loaded images (or a data-attribute if you may) and then compare they to the total images amount in the grid.
function checkGrid(image) {
const grid = image.closest('section');
const gridImages = grid.querySelectorAll('img');
const gridImagesWithError = grid.querySelectorAll('img.invalid-src');
if(gridImagesWithError.length === gridImages.length) {
grid.style.display = 'none';
}
}
document.addEventListener("DOMContentLoaded", function(event) {
const images = document.querySelectorAll('img');
images.forEach(function(image) {
image.onerror = function() {
this.classList.add('invalid-src');
this.style.display = 'none';
checkGrid(this);
};
});
});
Although this works, in order to check multiple grids, it is recommended that you add a class to the grids so the query selector wouldn't have to rely solely on the section tag which can be unsafe.
Upvotes: 1