Reputation: 1312
I am trying to add infinite scroll to my rails application using the will_paginate
gem and then using AJAX to fetch the next paginated page, but my javascript is not being rendered.
It seems like turbolinks is causing the problem. When I remove turbolinks the error goes away, but the script no longer runs. Below are my logs and script. Can anyone help me out?
This is the error I get from my logs:
ActionView::Template::Error (SyntaxError: [stdin]:5:2: unexpected if):
5: <!-- had to add the script to override JS error -->
6: <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
7: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
8: <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
9: <%= csrf_meta_tags %>
10: </head>
11: <body>
app/views/layouts/application.html.erb:8:in `_app_views_layouts_application_html_erb___2390735874352053488_70114430886900'
My links.js.coffee
jQuery ->
$(window).scroll ->
console.log('working')
if $(window).scrollTop() > $(document).height() - $(window).height() - 50
alert('next page')
Now if I take out the part of the script that compares the scroll placement to the doc height and window height the code works.
jQuery ->
$(window).scroll ->
console.log('working')
If you need to see any other information I'd be happy to provide it.
Upvotes: 0
Views: 911
Reputation: 3260
It looks like indentation issues to me. Coffeescript is whitespace sensitive. Try
jQuery ->
$(window).scroll ->
if $(window).scrollTop() > ($(document).height() - $(window).height() - 50)
alert('next page')
The differences here are
scroll
method call into the jQuery
onReady function.alert
under the if
As for the turbolinks issue, you can't simply use jQuery ->
(the onReady shortcut) to get everything to load. You probably need to add another listener.
So instead of:
jQuery ->
$(window).scroll ->
...
You might try something like this:
onPageReady = ->
$(window).scroll ->
if ...
$(document).ready(onPageReady)
$(document).on('page:load', onPageReady)
Very much like described here: Rails 4: how to use $(document).ready() with turbo-links
Hopefully that helps.
Upvotes: 1