Alt Text Generator

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

<script>

document.querySelectorAll('img').forEach(function(img) {
// Attach a load event listener to each image
img.addEventListener('load', function() {
var src = img.getAttribute('src') || img.getAttribute('data-src');
var fileNameMatch = src.match(/\/([^\/\?#]+)\.(jpg|jpeg|png|gif|bmp|tiff|
svg|webp)$/i);
if (fileNameMatch && fileNameMatch.length > 1) {
var altText = fileNameMatch[1].replace(/[-_]+/g, ' ').replace(/\b\w/g,
function(char) {
return char.toUpperCase();
});
img.setAttribute('alt', altText);
}
});

// If the image is already loaded, manually trigger the function


if (img.complete && img.naturalHeight !== 0) {
img.dispatchEvent(new Event('load'));
}
});
</script>

You might also like