Search code examples
jqueryturbolinks

jQuery scroll is working on pages it should not work on because of turbolinks


var paginationscript = function() {
  if($('#infinite-scrolling').size() > 0) {
    $('.pagination').hide();
    $('#load_more_photos').show();
    $('#load_more_photos').on('click', function() {
      var url = $('.pagination .next_page a').attr('href');
      $.getScript(url);
      $('#load_more_photos').hide();   
      $(window).on('scroll', function() {
        var url = $('.pagination .next_page a').attr('href')
        if($(window).scrollTop() > $(document).height() - $(window).height() - 60 && $.active == 0) {
        $.getScript(url);
        }
      });
    }); 
  }
};

So this creates an instagram-like setup where we first hide '.pagination' which is used if the user does not have js enabled, showing a button. They click that button and get the next page of photos. Then from there we use scroll to add the next pages. This all works fine.

The problem that with turbolinks enabled, it works on completely different parts of the app despite the fact that those pages do not contain the element '#infinite-scrolling'. Those pages do have $('.pagination .next_page a').attr('href') and that seems to be enough for turbolinks to enable the scroll function on those pages!

I tried to wrap the scroll function in if(window.location.pathname == "/photos") but that still did not help.

Edit: I added a script to the other pages $(window).off('scroll') and that does stop the scroll from working on those pages, however I would be interested in a better way to go about it.


Solution

  • i was able to solve this with the boolean of if(!(window.location.pathname == "/photos")) {}; thus turning off my scroll function upon leaving the page.