Currently, I am in the process of integrating the Load More button into a Ruby on Rails application. The implementation has been successful so far. However, there is an issue where the Load More button continues to appear even when there are no more photos left to be displayed.
Below are the code snippets:
<div class='container'>
<div class='section-header'>
<h2> Let's Rewind! </h2>
</div>
<div class='row'>
<div class='container'>
<div class='cust-cont'>
<%= render @scroll_photos %>
</div>
</div>
</div>
<div class="load-more-container">
<%= image_tag "ajax-loader.gif", style: "display:none;", class: "loading-gif" %>
<%= link_to "Load More", scroll_photos_path, class: "load-more" %>
</div>
</div>
_scroll_photo.html.erb
<div class="col-lg-12 col-md-4 col-xs-12">
<div class="image-box-4-3">
<div class="record" data-year="<%= scroll_photo.year %>">
<div class="image-content">
<%= image_tag(scroll_photo.image_link, width: "100%") %>
</div>
</div>
</div>
</div>
And here's the controller:
if params[:year]
# get all records with id less than 'our last id'
# and limit the results to 5
@scroll_photos = ScrollPhoto.where('year < ?', params[:year]).limit(2)
else
@scroll_photos = ScrollPhoto.limit(2)
end
respond_to do |format|
format.html
format.js
end
Javascript for handling the Load More functionality:
$(document).ready(function(){
// when the load more link is clicked
$('a.load-more').click(function(e){
// prevent default click action
e.preventDefault();
// hide load more link
$('.load-more').hide();
// show loading gif
$('.loading-gif').show();
// get the last id and save it in a variable 'last-id'
var last_year = $('.record').last().attr('data-year');
// make an ajax call passing along our last user id
$.ajax({
type: "GET",
url: $(this).attr('year'),
data: { year: last_year },
dataType: "script",
success: function(){
$('.loading-gif').hide();
$('.load-more').show();
}
});
});
});
index.js.erb
$('.cust-cont').append('<%= escape_javascript(render(:partial => @scroll_photos)) %>')