0

I'm attempting to create a page where a user can view pictures and like or dislike them. To make it user friendly, I'm creating a function that when a user clicks "load more post" jquery will fetch data from server.. I used append for this but javascript functions from the appended file don't work(function like lazy load, like and dislike) here is a sample of my code.

<div id='updatepost' class='col-md-12'></div>
<div class='col-md-12'>
<button class='btn btn-default' id='loadmore'>Load more post</button>
</div>

<script>
pages1 = 5;
pages2 = 10;
$("#loadmore").on("click", function(event) {
event.preventDefault();
loadData = 'pages1=' + pages1 + '&pages2=' + pages2;
    $.ajax({
    type: "GET",
    url: "loadpost.php",
    data: loadData,
    cache: false,
    success: function(html) {
    $("div#updatepost").prepend(html);
    }
    });

});
</script>
<script type='text/javascript' src='js/loadpost.js'></script>

and here's the loadpost.php and javascript functionsfor likepost, dislikepost and lazy load don't work anymore.

<img data-original='upload-image/uploads/myiamge.jpg'  class='lazy'>
<span class='likepost'>like</span>
<span class='dislikepost'>dislike</span>
Madara
  • 22
  • 5

1 Answers1

1

Use a lazy loader, which supports auto-initializing / self-initializing.

Otherwise you need to recall initialization code after append:

$("div#updatepost").prepend(html).find('img.lazyload').lazyload();

But in case you are using a lot of AJAX, I really suggest to use the lazySizes script linked above. The normal jQuery lazyload produces memory leaks on AJAX heavy sites.

For your like/dislike functionality you can use event delegation:

$('#updatepost').on('click, '.likepost', function(){
    //you like code
});
alexander farkas
  • 12,258
  • 3
  • 36
  • 40