Lightbox any Gutenberg image with Lity

I wanted an easy way to lightbox any image I added to my tutorials or snippets without having to rely on a different block or remembering to add a specific class.

I had a look at the Javascript lightbox options out there and Lity looked like the lightest and easiest option.

The best part…. It relies on 1 line of code!

Demo

Loading Lity

First we need to the enqueue the Lity.js and Lity.css files.

You can do this via CDN or loading them locally

Via CDN

https://cdn.jsdelivr.net/npm/[email protected]/dist/lity.min.js
https://cdn.jsdelivr.net/npm/[email protected]/dist/lity.min.css

Locally

If you are using advanced scripts you can copy everything in both files and paste into seperate snippets.

Otherwise, you can use Sridhars My Custom Functionality plugin.

https://github.com/jsor/lity/blob/master/dist/lity.min.js
https://github.com/jsor/lity/blob/master/dist/lity.min.css

Initialising Lity

Next, we need to add a Javascript click event.

jQuery(document).on('click', '.wp-block-image:not(.no-lightbox) > img', lity);

The selector we have used here is .wp-block-image > img which targets all images that are added via Gutenberg. As well as combining this with the :not selector which allows to exclude any elements that have the class .no-lightbox. This means if you have an image you don’t want lightboxed then it will not be triggered.

Styling

To add the nice zoom cursor hover effect:

.wp-block-image:hover:not(.no-lightbox){
    cursor: zoom-in;
}

Bonus

Looking to lightbox anything? Including videos (YouTube, Vimeo), google maps or URL.
I wrote a quick shortcode that allows you to do that.

function tct_lightbox($atts){
    return '<div class="lightbox"><a href="'.$atts['target'].'" data-lity>'. $atts['text'].'</a></div>';
}
add_shortcode( 'lightbox', 'tct_lightbox' );

Example:

[lightbox target="https://www.youtube.com/watch?v=dQw4w9WgXcQ" text="Click Me"]

Resources

Lity website – https://sorgalla.com/lity/
Lity Github – https://github.com/jsor/lity
:not Selector – https://developer.mozilla.org/en-US/docs/Web/CSS/:not

Leave a Comment