Skip to main content

Turn Images into Teasers

Place the following script either on the page or in the scripts tab to make it work site wide

Images to Teasers 

<script>
document.addEventListener("DOMContentLoaded", async function () {
    const figures = document.querySelectorAll(".poc-editor-image-container"); // Find all image containers

    for (const figure of figures) {
        const img = figure.querySelector("img"); // Get the image inside
        const caption = figure.parentElement.querySelector("figcaption div"); // Get the caption with URL

        if (!img || !caption) continue;

        const pageUrl = caption.textContent.trim(); // Extract the URL
        if (!pageUrl.startsWith("http")) continue; // Ensure it's a valid URL

        try {
            // Fetch the page content
            const response = await fetch(pageUrl);
            const text = await response.text();

            // Parse the fetched HTML
            const parser = new DOMParser();
            const doc = parser.parseFromString(text, "text/html");

            // Get the full title
            let pageTitle = doc.querySelector("title")?.textContent.trim() || "External Page";

            // Clean the title: Remove website name
            const delimiters = [" - ", " | ", " : "]; // Common separators
            delimiters.forEach(delimiter => {
                if (pageTitle.includes(delimiter)) {
                    pageTitle = pageTitle.split(delimiter)[0].trim(); // Keep only the first part
                }
            });

            // Get meaningful text: Meta description or first paragraph
            let previewText = doc.querySelector("meta[name='description']")?.getAttribute("content") ||
                              doc.querySelector("p")?.textContent.trim() ||
                              "No preview available.";

            // Limit preview length
            previewText = previewText.length > 200 ? previewText.substring(0, 200) + "..." : previewText;

            // Create the teaser
            const teaser = document.createElement("article");
            teaser.classList.add("poc-instance", "clearfix", "poc-type-page", "has-no-date", "has-image");

            teaser.innerHTML = `
                <a href="${pageUrl}" class="inner">
                    <div class="image">
                        <img src="${img.src}" alt="${img.alt}">
                    </div>
                    <header><h3><span>${pageTitle}</span></h3></header>
                    <p class="teaser"><span>${previewText}</span></p>
                    <footer><span class="call-to-action">Read more »</span></footer>
                </a>
            `;

            // Replace the image container with the new teaser
            figure.parentElement.replaceWith(teaser);
        } catch (error) {
            console.error(`Error fetching content from ${pageUrl}:`, error);
        }
    }
});
</script>