Search code examples
javascriptjqueryfotorama

Fotorama - different captions based on if element has attribute


I am trying to make a custom Fotorama caption appear differently depending on whether the img has a data-title attribute or not. Right now, it is currently appearing as "undefined," but I would like it to just omit that attribute altogether if it's not there. I tried using if/else statements and verifying whether the img element has that attribute or not, but to no avail. I am not able to use the "div" Fotorama approach because I need the gallery to be constrained and size images accordingly.

This is how my img tags are looking:

<img src="images/whatever.jpg" data-caption="Brief description goes here." data-author="Additional description here" data-title="http://www.link.com" border="0">

This is the code I am using to create the custom caption format:

$('.fotorama')
.on('fotorama:show', function (e, fotorama) {
fotorama.$caption = fotorama.$caption || $(this).next('.example_blurb');
var activeFrame = fotorama.activeFrame;
fotorama.$caption.html(
  '<p><em>' + activeFrame.caption + ' <a target="_blank" href="' + activeFrame.title + '">(link)</a></em></p><p>' + activeFrame.author + '</p>'
);
})
.fotorama();

And this is how I want the caption to read if there is no data-title attribute on the div:

'<p><em>' + activeFrame.caption + '</em></p><p>' + activeFrame.author + '</p>'

Thanks in advance!


Solution

  • Figured out a workaround for this using CSS if anyone else is having the same issue. I battled with creating if...else statements for how the caption would display based on whether or not the data-title attribute was defined, but for some reason it didn't seem to check each activeFrame for whether it had the data-title attribute or not-- only the first. Could be an inherent issue with the plugin or me overlooking something.

    Anyways, the solution!

    I made a new attribute on each img tag ("data-class"), which will either have the value "work_link" or "no_link":

    <img src="images/whatever.jpg" data-caption="Brief description goes here." data-author="Additional description here" data-title="http://www.link.com" data-class="work_link" border="0">
    <img src="images/whatever.jpg" data-caption="Brief description goes here." data-author="Additional description here" data-class="no_link" border="0">
    

    I changed the caption HTML in the script to read like so-- essentially giving the link either the "work_link" or "no_link" class:

    fotorama.$caption.html(
      '<p><em>' + activeFrame.caption + '<a class="' + activeFrame.class + '" target="_blank" href="' + activeFrame.title + '">(link)</a></em></p><p>' + activeFrame.author + '</p>'
    );
    

    And finally made the "work_link" class have basic styling CSS, and the "no_link" class not display.

    .work_link { margin-left: 12px; }
    .no_link { display: none; }
    

    Perhaps not the cleanest way to do it, but works like a charm!