Flyfish's Blog

Implement an Image Lightbox For Your Bearblog

One feature I’ve been missing since I started using Bearblog is an image lightbox. Viewing images without enlarging them really drives me mad. Even one of my friend asked me about this feature. So I have one implemented.

Lightbox Example

Click the image to see it yourself

In this post I will guide you to setup an image light box for your own Bearblog with a few lines of code.

Important note: You need an upgraded account to do this, javascript is used.

Just copy&paste the following script into Footer Directive in Settings > Header and footer directives.

<script>
    document.addEventListener("DOMContentLoaded", function () {
        let lightbox = document.createElement("div");
        lightbox.id = "lightbox";
        document.body.appendChild(lightbox);

        let img = document.createElement("img");
        lightbox.appendChild(img);

        lightbox.addEventListener("click", () => {
            lightbox.style.visibility = "hidden";
            lightbox.style.opacity = "0";
        });

        document.querySelectorAll("img").forEach(image => {
            image.style.cursor = "pointer";
            image.addEventListener("click", () => {
                img.src = image.src;
                lightbox.style.visibility = "visible";
                lightbox.style.opacity = "1";
            });
        });
    });
</script>

This code applies Lightbox effect to all the images.

CSS

Also use the following CSS.

/* Image Lightbox */
#lightbox {
    position: fixed;
    top: 0; left: 0; width: 100%; height: 100%;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    visibility: hidden;
    opacity: 0;
    transition: opacity 0.3s ease-in-out;
}
#lightbox img {
    max-width: 90%;
    max-height: 90%;
}
#lightbox:target {
    visibility: visible;
    opacity: 1;
}

Like this post if it had helped you :)

#bearblog #code #post