Search/static/js/imagetitletrim.js

56 lines
No EOL
2.1 KiB
JavaScript

document.addEventListener('DOMContentLoaded', function() {
let imagesContainer = document.querySelector('.images');
let observer;
// Function to trim image titles based on the image width
function trimTitles() {
const images = document.querySelectorAll('.images .image');
images.forEach((element) => {
const imgElement = element.querySelector('img.clickable');
const titleElement = element.querySelector('.img_title.clickable');
const detailsElement = element.querySelector('.details');
if (imgElement.complete && imgElement.naturalWidth) {
const imageWidth = imgElement.clientWidth;
// Set the width of the details div and title to match the image width
detailsElement.style.width = imageWidth + 'px';
titleElement.style.maxWidth = imageWidth + 'px';
}
// // Add load event listener in case images load dynamically
// imgElement.addEventListener('load', function() {
// const imageWidth = imgElement.clientWidth;
// detailsElement.style.width = imageWidth + 'px';
// titleElement.style.maxWidth = imageWidth + 'px';
// });
});
}
// Call trimTitles periodically to account for dynamic loading, not happy about this one
setInterval(() => {
trimTitles();
}, 10);
// Observe for dynamically added images
function observeNewImages() {
observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
mutation.addedNodes.forEach(function(node) {
if (node.nodeType === 1 && node.classList.contains('image')) {
trimTitles();
}
});
});
});
// Observe the images container for changes
observer.observe(imagesContainer, { childList: true, subtree: true });
}
// Run initial title trimming after page load
trimTitles();
// Start observing for dynamic image loading
observeNewImages();
});