0

I'm looking to set a "scroll up" button using JQuery for my rails application. Here's the JQuery script:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        $(window).scroll(function() {
            if($(this).scrollTop() > 300) {
                $('#toTop').fadeIn();
            } else {
                $('#toTop').fadeOut();
            }
        });
        $('#toTop').click(function() {
            $('body,html').animate({scrollTop:0},300);
        });
    });
</script>

Here's CSS for the button:

#toTop {
    width:100px;
    text-align:center;
    padding:5px;
    position:fixed;
    bottom:5px;
    left:50%;
    cursor:pointer;
    display:none;
    color:#333;
    font-size:20px;
    &:hover {
      color:  #8B0000;
    }
}

When I open a new page, say localhost:3000/signup, the button scrolls up just fine. But if I click on another page, the scroll event doesn't happen. Thus, the button works properly either if I reload the page or open a new one in another tab. What might cause the problem?

Dekel
  • 60,707
  • 10
  • 101
  • 129
  • what is `another page` – brk Sep 06 '16 at 12:21
  • Have you tried looking at the browser console to see if there are any errors? – max Sep 06 '16 at 12:25
  • 2
    Do you have [turbolinks](http://stackoverflow.com/questions/18770517/rails-4-how-to-use-document-ready-with-turbo-links) turned on? Your event listener may not be listening for these events. – Cory J. Sep 06 '16 at 12:26
  • `Cory J.` Yep, I added `turbolinks:load` and it solved the issue. Thanks! –  Sep 06 '16 at 12:46

2 Answers2

0

Turbolinks works by fetching the content of a link via AJAX and replacing the contents of the document - this speeds up page loading quite a bit.

One consequence of this is that the "document ready" event is only fired once in the page cycle when a page is initially opened in the browser.

So when the content is replaced the event handler that you have attached to the #toTop element is no longer there.

A better way to do this is by using event delegation

// remember that this is a shorthand for $(document).ready
$(function() {
  $(document).on('click', '#toTop', function(){
    $('body,html').animate({ scrollTop: 0 }, 300);
  });
});

This binds the event handler to the document instead of directly to the element. See https://github.com/turbolinks/turbolinks

max
  • 96,212
  • 14
  • 104
  • 165
  • Note that Turbolinks 5 is a complete rewrite and that you might need to look at the documents for https://github.com/turbolinks/turbolinks-classic for older versions of turbolinks. – max Sep 06 '16 at 12:47
0

I wrapped the Jquery script with this line and it did the trick:

    $(document).on('turbolinks:load', function() {

   // ...script for button 

    });