I recently implemented endless page scrolling as seen in the [blog post](http://christianvarga.com/2013/02/simple-infinite-scroll-with-rails-and-jquery/). In summary, I show 10 posts on a page, when the user reaches the bottom of the page, the app fires a 'get' request to the index action, loads 10 more posts and appends them to the page with jquery.

Here is my implementation:

post\_controller

```
def index
if params[:tags]
  @posts = Post.tagged_with(params[:tags]).paginate(:page => params[:page], :per_page => 10)
else
  @posts = Post.paginate(:page => params[:page], :per_page => 10)
end

respond_to do |format|
  format.html
  format.js { render 'index.js.erb'}
end
end

```

index.js.erb

```
$('#posts').append('<%= escape_javascript(render @posts) %>');
$('a.load-more-posts').attr('href', '<%= posts_path page: @posts.next_page %>');

<% unless @posts.next_page %>
  $('a.load-more-posts').remove();
<% end %>

```

I run into some issues when I try to filter the posts by tag. The root problem is that the same `index.js.erb` file gets fired when a user manually clicks a tag to see posts with that tag and also by the endless scroll function.

When a new tag is clicked, rather than the posts just be appended to the existing html, the displayed posts should first be cleared and then the new posts should be appended. 

From that point it seemed obvious that I should separate out the index action and a separate `posts_tagged_with` action. This action would have its own js file that is very similar, but it will replace html rather than append. 

The problem with this is that the original `index.js.erb` is still called when the user scrolls down, which appends posts from index action.

Is there a better implementation for this?