Search/static/js/imagetitletrim.js

57 lines
2.2 KiB
JavaScript
Raw Normal View History

2024-10-22 10:46:47 +02:00
/*
This script is responsible for trimming image title/name on the image results page. (Since I haven't figured out how to make this work in CSS.)
*/
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) => {
2024-12-03 14:37:25 +01:00
// Skip if the image has already been processed
if (element.classList.contains('checked')) return;
const imgElement = element.querySelector('img.clickable');
const titleElement = element.querySelector('.img_title.clickable');
const detailsElement = element.querySelector('.details');
2024-12-03 14:37:25 +01:00
// Only process if the image is fully loaded
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';
2024-12-03 14:37:25 +01:00
// Mark this image as processed and add it to the "checked" blacklist
element.classList.add('checked');
}
});
}
2024-12-03 14:37:25 +01:00
// Run trimTitles periodically every 500ms
setInterval(trimTitles, 500);
// Observe for dynamically added images
function observeNewImages() {
observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
mutation.addedNodes.forEach(function(node) {
2024-12-03 14:37:25 +01:00
if (node.nodeType === 1 && node.classList.contains('image') && !node.classList.contains('checked')) {
trimTitles(); // Call trimTitles for newly added image
}
});
});
});
// 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();
});