Search code examples
jqueryphotoswipe

use photoswipe on dynamically created ul


I am working on a jquery mobile site which will have an image gallery populated by JSON/AJAX from instagram. I can get the images loaded just fine, but I want to take it one step further and use photoswipe to render the gallery. The issue that I am running into, is that if I add the call to photoswipe after the ul has been populated from the json feed, the ul has not actually been redrawn, so photoswipe can't find any child elements to use. Below is my script:

HTML

<div data-role="page" id="Photos">
<div data-role="header">
    <a href="javascript:history.go(-1)" data-icon="back" data-direction="reverse">Back</a>      
    <h1>Photos</h1>
</div>
<div data-role="content">   
    <div id="AdBanner">
    </div>
    <ul id="PhotoList">
    </ul>
</div>
</div>

Script

$("#Photos").live("pagebeforeshow", function(){
    $("ul#PhotoList").children().remove('li');
    var tag = MyTag
    $.getJSON("https://api.instagram.com/v1/tags/" + tag + "/media/recent?callback=?&amp;client_id=####",
    function(data){
        $.each(data.data, function(i,item){
            $("ul#PhotoList").append('<li><a href="' + item.images.low_resolution.url + ' rel="external"><img src="' + item.images.low_resolution.url + '" alt="' + item.caption.text + '" width="200" /></a></li>');
        });
    });
    var photoSwipeInstance = $("ul#PhotoList a").photoSwipe();
});

Is there a way to refresh the ul prior to calling the photoswipe initiator, or is there another event that I should be using for photoswipe?


Solution

  • I'm sure that this is not the "proper" answer to this question, but I did find a work-around to get the functionality that I wanted. Rather than using jquery ul.append to add the list items, I instead used a variable to add the list item to the variable, and then set the UL.innerhtml to the variable:

    var Photos = "";
    $.each(data.data, function(i,item){
        Photos += '<li><a href="' + item.images.low_resolution.url + '"><img src="' + item.images.low_resolution.url + '" alt="' + item.caption.text + '" width="80" /></a></li>';
    });
    document.getElementById('PhotoList').innerHTML = Photos;
    

    Again, I am sure that this is not the correct way to do this, but it works for me, and in the absence of a better solution, it got the job done.