maryanne maryanne - 11 months ago 49
jQuery Question

Scroll event doesn't work unless the page is reloaded

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

<script src=""></script>
<script type="text/javascript">
$(function() {
$(window).scroll(function() {
if($(this).scrollTop() > 300) {
} else {
$('#toTop').click(function() {

Here's CSS for the button:

#toTop {
&: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?

max max
Answer Source

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