Reputation: 383
I'm new to javascript/jquery and will admit I'm not sure how it all works at the moment, I've been doing a lot of googling to get this far! So I have a site that is using masonry.js to display items in a pinterest type way. Now the first page loads fine and is laid out as expected. When the user scrolls to the bottom of the page, my new content gets added in the right place on the screen BUT the old content is gone! The new content is added in the right place but everything before it is blank! This so nearly works, I just can't see why the scroll function is appending content but removing the original!
The code that loads the initial content is:
<script type="text/javascript">
$(document).ready(function() {
var $grid = $('.grid').masonry({
// set itemSelector so .grid-sizer is not used in layout
itemSelector: '.grid-item',
// use element for option
columnWidth: '.grid-sizer',
gutter: 10
})
});
var track_load = 0; //total loaded record group(s)
var loading = false; //to prevents multiple ajax loads
var total_groups = <?php echo $total_groups; ?>; //total record group(s)
var leagueid = <?php echo "1";?>;
var content = $('.grid').load("league_news1.php", {'group_no':track_load,'leagueid':leagueid}, function() {track_load++;
$(".grid").imagesLoaded(function() {
$(".grid").append(content).masonry("appended", content);
});
});
</script>
And then this is what I use to add more content when the user scrolls:
<script type='text/javascript'>
$(window).scroll(function() { //detect page scroll
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 60) {
if(track_load <= total_groups && loading==false) //theres more data to load
{
loading = true; //prevent further ajax loading
$('.animation_image').show(); //show loading image
//load data from the server using a HTTP POST request
var new_content = $('.grid').load("league_news1.php", {'group_no':track_load,'leagueid':leagueid}, function() {
$(".grid").imagesLoaded(function() {
$(".grid").append(new_content).masonry("appended",new_content);
//hide loading image
$('.animation_image').hide(); //hide loading image once data is received
track_load++; //loaded group increment
loading = false;
}).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
alert(thrownError); //alert with HTTP error
$('.animation_image').hide(); //hide loading image
loading = false;
});
});
}
}
});
</script>
Upvotes: 0
Views: 218
Reputation: 383
After speaking with the developer of the plugin (although it was my jquery that was at fault, not his excellent plugin) the answer was to wrap content in a jquery object like so:
$.get("league_news.php", {'group_no':track_load,'leagueid':leagueid}, function(data) {
track_load++;
var $content=$(data);
$content.imagesLoaded(function() {
$(".grid").append($content).masonry("appended", $content);
});
});
Upvotes: 0