user2997418 user2997418 - 3 months ago 19
HTML Question

jPages doesn't recongnise images added dynamically with jQuery

I have a html, JS script that loads images from PHP/AJAX and put them into a div, a JS will paginate it after that.
when I try manually hardcode my images, all is fine, when I load the images with jquery, the script doesnt paginate them, even when I tried

$(document).ready


(you can find ipages.js here : http://luis-almeida.github.io/jPages/js/jPages.js)
HTML:

<script src="js/jPages.js"></script>
...
<ul id="itemContainer">
<li><img src="images/test/img (1).jpg" alt="image"></li>
<li><img src="images/test/img (2).jpg" alt="image"></li>
<li><img src="images/test/img (3).jpg" alt="image"></li>
<li><img src="images/test/img (4).jpg" alt="image"></li>
<li><img src="images/test/img (5).jpg" alt="image"></li>
<li><img src="images/test/img (6).jpg" alt="image"></li>
<li><img src="images/test/img (7).jpg" alt="image"></li>
</ul>


JS:

$(document).ready(function() {
/* initiate plugin */
$("div.holder").jPages({
containerID: "itemContainer"
});
});


This above works. Now, if I try to append the itemContainer with jQuery, it doesnt work. I see the images but no pagination:
AJAX:

$(function ()
{
$.ajax({
url: 'models/fetchUsers.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append('<li><img src="images/profiles/'+value.user_id+'/'+value.profile_pic+'" alt="image"></li>');
});
}
});
});

Answer

try this code. You are initiate plugin on document ready. So when dom is ready all current html paginate perfectly. But after doing ajax request you are adding new html element which are dead elements and which are still uninitialized so that html needs to initialized again. So on ajax success request I reinitialized jPages plugin and It works

$.ajax({
        url: 'models/fetchUsers.php',    //the script to call to get data
        dataType: 'json',                //data format
        success: function(data)          //on recieve of reply
        {
            $.each($(data), function(key, value) {
                $('#itemContainer').append('<li><img src="images/profiles/'+value.user_id+'/'+value.profile_pic+'" alt="image"></li>');
            });
            $("div.holder").jPages({
               containerID: "itemContainer"
            });
        }
    });