I’m starting a new side project, where I’ll have to insert lots of screenshots for each blogpost. I’d like to allow users to enlarge images without having to leave the current page. The best way to do this is with a “lightbox,” which darkens the background and displays the image in the center of the screen.
What I would like is just to post an image to the blog and have the lightboxing and image resizing occur automatically. Unfortunately none of the WordPress plugins let you do this; most of them require you to add an extra link with a special tag. So I wrote this short bit of Javascript which extends a popular WordPress lightbox plugin, Lightbox 2. The script takes an image and wraps an “a” tag around it with the rel=”lightbox” attribute set, which triggers the Lightbox code. It also resizes the image to a maximum of 600 pixels wide or high. Here’s the code:
//get all images inside entry content
jQuery(document).ready(function(){
jQuery(".entry-content img").each(function(){
//get the URL of the image
var the_url = jQuery(this).attr('src');
//insert a href before image where rel=lightbox
var a = jQuery("<a></a>").attr({"href": the_url, "rel": "lightbox"});
jQuery(this).wrap(a);
jQuery(this).load(function(){
var the_width = jQuery(this).width();
var the_height = jQuery(this).height();
var max_dimension = 600;
if (the_width && the_height){
var ratio = the_width / the_height;
if (ratio >= 1 && the_width > max_dimension){
jQuery(this).css('width', max_dimension);
jQuery(this).css('height', the_height * max_dimension / the_width);
}
else if (ratio > 1 && the_height > max_dimension){
jQuery(this).css('height', max_dimension);
jQuery(this).css('width', the_width * max_dimension / the_height);
}
}
});
});
});
You can also download the file here. To install, edit the header.php file of your WordPress directory and add the following lines above the
<?php wp_head(); ?>
line:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script src="/path/to/img.js file" type="text/javascript"></script>
Then you’re done!
Liked what you read? I am available for hire.