Search code examples
jqueryfancyboxhref

jQuery FancyBox Plugin display gallery dynamically


I have a view in my CodeIgniter app. I am using fancybox to display user submitted images from a foreach php loop. My view looks like this:

<ul>
<?php
foreach($photo_strip['photos'] as $photo) { ?>
<li>
<a href="" class="fancybox" rel="group"><img src="<?= $photo->image ?>" alt=""/></a>
</li>
</ul>

here in <li> elements, I not only display images, but also link them. please note that images being displayed or in a thumbs folder. In order for thumb to display actual image, I am dynamically linking each thumbnail to its parent image by changing href path with Jquery. So here is my jQuery :

$(document).ready(function()
{
$('.fancybox').click(function()
{
    var srcPath = $(this).find("img").attr("src");
    var newFilename = srcPath.split('/').pop();
    var newPath = 'http://example.com/images/trip/' + newFilename;
});

So each time when a user clicks the thumnail saved in the directory: /trip/thumbs/, my jQuery changes the file path and loads actual image from: /trip/ This works well upto this point. But when I add fancybox to it, either it shows only thumbnails except the first clicked image, or it loads the same image despite clicking navigation buttons. So my full script looks like this:

$(document).ready(function()
{
$('.fancybox').click(function()
{
    var srcPath = $(this).find("img").attr("src");
    var newFilename = srcPath.split('/').pop();
    var newPath = 'http://example.com/images/trip/' + newFilename;
 $('.fancybox').attr("href", newPath);
 $('.fancybox').fancybox({
    padding: 0
});
 });
});

My problem is: I want to be able to click a single thumb, it opens fancybox, and when I navigate, it should open image from parent directory, not the thumb itself.

Is there anyway to do this?


Solution

  • Since fancybox builds the gallery from the collection of href values in each anchor (which are empty) it won't worth changing those values after a click (but for the first element) because, the navigation arrows of the fancybox gallery are not aware of the click event bound to the anchors with class fancybox. In other words, click events on the navigation arrows are not the same of those bound to elements with class fancybox.

    What you may need to use is the .each() method to add a data-fancybox-href attribute to your anchors before they are bound to fancybox. Then you can chain fancybox to the same selector.

    Additionally, since you are just changing the path of the <img> tag from /trip/thumbs/ to /trip/ you may use the .replace() method for simplicity, instead of declaring many variables with splits and pops like :

    jQuery(document).ready(function () {
        jQuery(".fancybox").each(function () {
            $(this).attr("data-fancybox-href", $(this).find("img").attr("src").replace("/trip/thumbs/", "/trip/"));
        }).fancybox({
            padding: 0
        });
    });
    

    See JSFIDLE