Skip to content

Instantly share code, notes, and snippets.

@ara303
Last active November 30, 2018 15:03
Show Gist options
  • Save ara303/5ce1ec3d0b1f69e80724af7eb3b606f4 to your computer and use it in GitHub Desktop.
Save ara303/5ce1ec3d0b1f69e80724af7eb3b606f4 to your computer and use it in GitHub Desktop.
Use Tumblr's built-in lightbox for displaying high-resolution images in a lightbox, basically "free" by leveraging code already in Tumblr. Updated for 2018: no longer requires jQuery, gets `low_res` attribute from image `src`, use more modern JS standards than when this was originally written in 2014!
<script>
let clbPhotos = document.querySelectorAll('.page-index .photo-image[data-highres]'); // Replace this with the selector for whatever you want to be the trigger.
Array.prototype.forEach.call(clbPhotos, function(clbElement, i){
clbElement.addEventListener('click', function(){
let clbAttrs = clbElement.dataset;
let clbData = [{
"width": clbAttrs.highresWidth,
"height": clbAttrs.highresHeight,
"low_res": clbElement.src, // My trigger is the image element so I can take the existing src that is currently being displayed. This is quite good for performance because I know that version is already loaded in. If you make the trigger anything else, you'll need to find another way to provide the low resolution version, it's not optional.
"high_res": clbAttrs.highres
}];
Tumblr.Lightbox.init(clbData, 1);
});
});
</script>
Example usage:
<img src="{PhotoURL-500}" class="photo-image" {block:HighRes}data-highres="{PhotoURL-HighRes}" data-highres-width="{PhotoWidth-HighRes}" data-highres-height="{PhotoHeight-HighRes}"{/block:HighRes}>
Working demo: https://codepen.io/edadams/pen/gQQVOj?editors=1111
About:
Tumblr exposes a function called Lightbox.init that lets you trigger a custom lightbox with whatever you want in it. On the Tumblr Dashboard, apps, and default theme, clicking on an image will show the full-size in a nice lightbox. That function can be used custom as seen above.
The magic lies in the data-highres-* attributes that I have added to the image. I'm looking for any images with a data-highres attribute, as well as several others that are necessary for the lightbox function to work. Mercifully Tumblr exposes all the data you need for you.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment