Question

I am trying to load content in from sub pages and then add the rel attribute for a gallery required by the prettyPhoto plug in. After the script runs the rel has only been added to the last set of images.\

HTML

<div class="prettyphotothumb">
    <ul class="navsub">
    <li><a href="album.html"><img src="images/thumbnail.jpg" alt="" />Album</a></li>
    <li><a href="blarg.html"><img src="images/thumbnail.jpg" alt="" />Blarg</a></li>
    <li><a href="test.html"><img src="images/thumbnail.jpg" alt="" />Test</a></li>
    </ul>
</div>

JS

if($('div.prettyphotothumb').length > 0) {
    $('div.prettyphotothumb a').each(function() {
        var pageLink = $(this);
        var albumTitle = $(pageLink).text();
        var album = $('<div class="album"></div>').appendTo( $(pageLink).parent());

        $('.album').load(this.href+' .prettyphotoalbum p > *',null,function(){  
            album.children('a').attr('rel','prettyPhoto['+albumTitle+']');
        });

        $('a[rel^="prettyPhoto"]').live("click",function() {
            $.prettyPhoto.open($(this).attr("href"),"","");
            return false;
        });         

    }); 
}
Was it helpful?

Solution

As you iterate using each, you're adding a <div class="album"> on each iteration:

var album = $('<div class="album"></div>').appendTo( $(pageLink).parent());

And then right below that:

$('.album').load(//...

On the first iteration, $('.album').length will be one, on the second it will be two, etc. The final iteration will end up calling .load('test.html .prettyphotoalbum p > *', ... on all three <div class="album"> elements that you've added.

I think you want to just bind the load to the thing you just created:

// Use album rather than $('.album')
album.load(this.href+' .prettyphotoalbum p > *',null,function(){  
    album.children('a').attr('rel','prettyPhoto['+albumTitle+']');
});

Also, you only need one .live call so move this:

$('a[rel^="prettyPhoto"]').live("click",function() {
    $.prettyPhoto.open($(this).attr("href"),"","");
    return false;
});

outside the .each. So something like this should work better:

if($('div.prettyphotothumb').length > 0) {
    $('div.prettyphotothumb a').each(function() { 
        var pageLink   = $(this);
        var albumTitle = $(pageLink).text();
        var album      = $('<div class="album"></div>').appendTo($(pageLink).parent());

        album.load(this.href+' .prettyphotoalbum p > *', null, function() { 
            album.children('a').attr('rel', 'prettyPhoto[' + albumTitle + ']');
        });
    });

    $('a[rel^="prettyPhoto"]').live("click", function() {
        $.prettyPhoto.open($(this).attr("href"), "", "");
        return false;    
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top