ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina
Introduction of 1 gem 2 Introduction of jscroll 3 Edit controller 4 Edit view Edit 5 js 6 CSS editing
Gemfile
gem 'jquery-rails'
gem 'kaminari'
Terminal
$ bundle install
$ rails g kaminari:config
$ rails g kaminari:views default
app/assets/javascripts/application.js
//=require jquery ← added
//= require jquery_ujs ← added
//= require activestorage
//= require turbolinks
//= require_tree .
Reference: kaminari [Ruby on Rails] Paging function introduced
Introduce in ① or ②.
①https://github.com/pklauzinski/jscroll/tree/master After downloading the zip file from this GitHub, jquery.jscroll.min.js in dist Please save it under app / asset / javascripts.
(2) Use this when writing in the head.
python
<script src="https://cdnjs.cloudflare.com/ajax/libs/jscroll/2.4.1/jquery.jscroll.min.js"></script>
After introducing ① or ②, describe as follows.
app/assets/javascripts/application.js
//= require jquery
//= require jquery_ujs
//= require jquery.jscroll.min.js ← added
//= require activestorage
//= require turbolinks
//= require_tree .
By writing .page (params [: page]) .per (20) Shows 20 elements.
app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.page(params[:page]).per(20)
end
end
Edit the class name in the div with jQuery.
erb:app/viws/posts/index.html.erb
<div class="scroll-list jscroll">
<% @posts.each do |post| %>
<span><%= post.post_title %></span>
<% end %>
<%= paginate @posts %>
</div>
This time when scrolling to the bottom 5% of the screen Try to load a new one.
app/assets/javascripts/application.js
$(window).on('scroll', function() {
scrollHeight = $(document).height();
scrollPosition = $(window).height() + $(window).scrollTop();
if ( (scrollHeight - scrollPosition) / scrollHeight <= 0.05) {
$('.jscroll').jscroll({
contentSelector: '.scroll-list',
nextSelector: 'span.next:last a'
});
}
});
app/assets/stylesheets/application.scss
nav.pagination {
display: none;
}
.scroll-list {
padding: 0;
}
Infinite scrolling is also used on Twitter and Instagram, so If there are many displays, it is a function that should be introduced.
Also, on twitter, technologies and ideas that have not been uploaded to Qiita are also uploaded, so I would be grateful if you could follow me. Click here for details https://twitter.com/japwork
Recommended Posts