Search code examples
javascriptjqueryfancyboxfancybox-2

Fancybox Observer across multiple links?


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?


Solution

  • 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.