16

I'd like to know how I can add more than a title (e.g a caption or a link) to the fancybox. I am aware that if I add a title="Bla" it'll show up in the box. But if I add something like caption="Blabla" to my image link, what code do I need to have in jquery.fancybox.js to pull that caption tag?

Jean
  • 313
  • 2
  • 5
  • 16
  • 1
    possible duplicate of [Fancybox 2 Custom Titles and Captions \[from A(title) and IMG(alt\]](http://stackoverflow.com/questions/9058442/fancybox-2-custom-titles-and-captions-from-atitle-and-imgalt) – Ankur Feb 28 '14 at 06:15

2 Answers2

39

You don't need to mess with original jquery.fancybox.js file since you could add this option within your own customized fancybox script.

If you are using HTML5 DOCTYPE, you could use the data-* attribute for you caption so you can have this HTML :

<a class="fancybox" href="images/01.jpg" data-caption="This is the caption" >Open fancybox</a>

Then set your custom fancybox script and get the data-caption using the beforeShow callback like

$(document).ready(function() {
 $('.fancybox').fancybox({
  beforeShow : function(){
   this.title =  $(this.element).data("caption");
  }
 });
}); // ready

That will override the title and use the data-caption instead.

On the other hand, you may want to keep the title attribute and build the fancybox's title combining both, title and data-caption attributes so, for this HTML

<a class="fancybox" href="images/01.jpg" title="This is the title" data-caption="This is the caption">Open fancybox</a>

Use this script

$(document).ready(function() {
 $('.fancybox').fancybox({
  beforeShow : function(){
   this.title =  this.title + " - " + $(this.element).data("caption");
  }
 });
}); // ready

Additionally, you could also get the caption/title from another HTML element within your document (a <div> for instance) that can have links or other HTML elements. Check these posts for code examples: https://stackoverflow.com/a/9611664/1055987 and https://stackoverflow.com/a/8425900/1055987

NOTE : this is for fancybox v2.0.6+

Community
  • 1
  • 1
JFK
  • 40,963
  • 31
  • 133
  • 306
  • Perfect elegant solution. Thank you! – Tim Bowen Oct 11 '15 at 16:22
  • @JFK Is there a way to keep/hold the caption visible? In my environmet, the captions disappears after some seconds. – The Bndr Aug 30 '17 at 12:29
  • @TheBndr The captions shouldn't ever disappear http://jsfiddle.net/picssel/1wn1f88b/ ... check you don't have code that actually removes the source of the captions after a time out or so (or reproduce the issue in a fiddle) – JFK Sep 12 '17 at 18:47
10

Old question, but thanks to JFK's answer I found out that with the latest version of fancybox you can add a caption simply by entering a value in the title="" attribute (by default). Just make sure it's included on the <a> element with the fancybox class.

Brad Adams
  • 2,066
  • 4
  • 29
  • 38