Monday, 1 July 2013

PrettyPhoto: How to make your captions use HTML formatting…

A PrettyPhoto gallery image using HTML styled caption

…without messing up the tooltips

I’ve been using PrettyPhoto for a while now, as it’s a nice and neat Lightbox effect for image galleries written in jQuery. It creates an overlay on the screen displaying the full size image from a thumbnail with navigation through related images. It’s always been possible to add captions to these large images, but with the last couple of versions there has been support for using HTML formatting tags to make the captions more attractive. Unfortunately the drawback of this is that the HTML is then displayed in plain text within the Tooltip when you hover over an image which is in a PrettyPhoto gallery. There is lots of information online about fixing this, but none of this is compatible with the current version of PrettyPhoto (v 3.1.5), so I decided to use the old fix as a basis for creating a way to pretty up the captions in the latest version.

Open the jquery.prettyPhoto.js file from your site and locate the line that contains the following code:
pp_descriptions=isSet?jQuery.map(o,function(t,n){if(e(t).attr(settings.hook).indexOf(theRel)!=-1)return e(t).attr("title")?e(t).attr("title"):""}):e.makeArray(e(this).attr("title"));
This tells the jQuery code to display the contents of the “title” tag of the image as the caption. This means that if you place HTML formatting code into the “title” tag of an image it will then appear fully formatted in the caption of the relevant PrettyPhoto gallery. However, the “title” tag is also used by browsers to display a description of the photo as a Tooltip when you hover over an image on the page. If you have added any HTML code here it will not be rendered by the browser as anything but text e.g.<h2>Heading</h2><p>Caption here.</p> will display formatted in the PrettyPhoto gallery, but exactly as written in the tooltip.

So, if we change the above line to use “alt” instead of “title” we can place plain text in the “title” attribute of our image to display as a tooltip, but place HTML formatted text in the “alt” attribute to allow PrettyPhoto to display a nicely formatted caption under our image in the gallery.

The new line will look like this:
pp_descriptions=isSet?jQuery.map(o,function(t,n){if(e(t).attr(settings.hook).indexOf(theRel)!=-1)return e(t).attr("alt")?e(t).attr("alt"):""}):e.makeArray(e(this).attr("alt"));
 And your image code will then look like this:
<ul class="gallery clearfix">
<a href="assets/large/photo-name.jpg" rel="prettyPhoto[galleryname]" title="This is a caption. This caption has no formatting for the title tag, used as a tooltip in the browser.” alt="<h2> This is a caption. </h2> This caption has no formatting for the title tag, used as a tooltip in the browser."><img src="assets/photo-name.jpg" alt="" /></a>
</ul>