Have searched for a solution to this but am coming up blank. I'm trying to set a data attribute and access it within the fancyBox options.
My anchor links looks like this:
<a class="expand" rel="gallery" href="/assets/images/larger-image.png" data-source="Some string" data-id="Some number">
<img src="blah.jpg" />
</a>
And my JS:
$(".expand").fancybox({
'padding' : 0,
'tpl' : {
image : '<img class="fancybox-image" src="{href}" alt="" />'
}
});
What I'd like to be able to do is access those data-attributes inside the tpl
option.
$(".expand").fancybox({
'padding' : 0,
'tpl' : {
image : '<h2>' + $(this.element).data('source') + '</h2><img class="fancybox-image" src="{href}" alt="" /><h3>' + $(this.element).data('id') + '</h3>'
}
});
I can't access this.element
in that context; is there an elegant way to achieve this?
Well, the tpl
is used to format specific elements of the fancybox structure so this
'tpl' : {
image : '<h2>' + $(this.element).data('source') + '</h2><img class="fancybox-image" src="{href}" alt="" /><h3>' + $(this.element).data('id') + '</h3>'
}
it's a bit odd since you are adding elements that are not part of the image
template (normally you would use it to add classes or other attributes , etc.)
Anyways, if this is what you want, you first need to use a fancybox callback to have access to the data
attributes ( $(this.element)
can only be accessed inside a callback ).
Then you may need to use the jQuery.extend()
method to modify the fancybox template on the fly (from within the afterLoad
callback) like :
$(".expand").fancybox({
afterLoad: function () {
$.extend(this, {
tpl: {
image: '<h2>' + $(this.element).data('source') + '</h2><img class="fancybox-image" src="{href}" alt="" /><h3>' + $(this.element).data('id') + '</h3>'
}
});
}
});
See JSFIDDLE
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.