supersize
supersize

Reputation: 14773

give img title a style for later use in fancybox

I'm using Fancybox and it uses the title="" attribute of images to fill the caption of each image. The problem I have is now, that I want to have some words of the caption styled different. The title of each img is created from an array:

var img = '<a class="fancybox" title="'+ imgArr[i].forname + ' ' + imgArr[i].surname +'" rel="group1"></a>'

and what I try to do is give imgArr[i].forname a bolder font so my attempt was:

var img = '<a class="fancybox" title="<span style="font-weight: 800;"'+ imgArr[i].forname + '</span> ' + imgArr[i].surname +'" rel="group1"></a>'

unfortunenately it does not work. Any clou?

Upvotes: 0

Views: 239

Answers (1)

JFK
JFK

Reputation: 41143

First, I would advise you to set the captions inside a (HTML5) data-* attribute instead, so when the visitor hovers the link they don't see your <span> code.

Second, you have to be very careful with the syntax, mostly when you nest quotes inside other quotes because you could close your declarations earlier than expected; for instance this line of your code:

var img = '<a class="fancybox" title="<span style="font-weight: 800;"'+ imgArr[i].forname + '</span> ' + imgArr[i].surname +'" rel="group1"></a>'

... the opening double quote of the style attribute (style="") in the <span> tag is actually closing the title attribute of the <a> tag, which is also using double quotes, so your code breaks here. Also notice that the <span> tag is not properly set, you are doing something like

<span style="font-weight: 800;"{forname} {surname}</span>

...because you forgot to place > just after the style attribute.

So try this code :

var img = '<a class="fancybox" data-title="<span style=\'font-weight: 800;\'>' + imgArr[i].forname + '</span> ' + imgArr[i].surname + '" rel="group1" href="{target}"></a>'

Notice how I used and escaped the quotes. Also notice I used the data-title attribute instead of title (I also set an href attribute in case you were missing it ;)

Then, get the data-title value inside the beforeShow callback in your fancybox custom script like :

$(".fancybox").fancybox({
    beforeShow: function () {
        this.title = this.element.data("title");
    } // , // <== comma if other options following
    // your other API options here
});

See JSFIDDLE

Upvotes: 1

Related Questions