0

If I have this markup:

<a href="#" data-fancybox-content="<p>Content 1</p>"> Click Here for Content 1</a>
<a href="#" data-fancybox-content="<p>Content 2</p>"> Click Here for Content 2</a>
<a href="#" data-fancybox-content="<p>Content 3</p>"> Click Here for Content 3</a>
<a href="#" data-fancybox-content="<p>Content 4</p>"> Click Here for Content 4</a>

And I want to set up my fancybox observer for each of those, but I want the content of the popup set to each link's data-fancybox-content, is there a way to do that in one fell swoop?

Joshua Soileau
  • 2,933
  • 9
  • 40
  • 51

2 Answers2

1

You don't need the .each() method but use the regular fancybox initialization script to bind your selectors (or elements) to fancybox, so

<a class="fancybox" href="#" data-content="<p>Content 1</p>"> Click Here for Content 1</a>
<a class="fancybox" href="#" data-content="<p>Content 2</p>"> Click Here for Content 2</a>
<a class="fancybox" href="#" data-content="<p>Content 3</p>"> Click Here for Content 3</a>
<a class="fancybox" href="#" data-content="<p>Content 4</p>"> Click Here for Content 4</a>

Notice that is not a good idea to bind javascript events to global elements (HTML tags) but use specificity (CSS selectors) instead, so we added the class fancybox to the elements we want to bind to fancybox.

Also notice that we only used data-content instead of data-fancybox-content attributes (data-fancybox-{something} is an special attribute that has no value for content)

Then you can set the content dynamically using the beforeLoad callback like :

jQuery(document).ready(function ($) {
    $('.fancybox').fancybox({
        beforeLoad: function () {
            this.content = $(this.element).data("content");
        }
    });
}); // ready

See JSFIDDLE

PS. you could even set a fancybox gallery by setting a rel or data-fancybox-group attribute to your elements. You wouldn't be able to do that with the .each() method.

JFK
  • 40,963
  • 31
  • 133
  • 306
  • is there a way to do this for dynamically generated links? http://stackoverflow.com/questions/34534759/create-a-simple-modal-pop-up-window-in-xslt – Ankit Vora Dec 30 '15 at 21:24
  • @ankk : this is for fancybox v2.x which supports dynamically added elements. For fancybox v1.3.x check http://stackoverflow.com/a/9084293/1055987 – JFK Dec 31 '15 at 17:00
0

Figured it out, here's how I did it:

$('a').each(function() {
    $(this).fancybox({
        content: $(this).attr('data-fancybox-content'),
    });
});
Joshua Soileau
  • 2,933
  • 9
  • 40
  • 51