maryanne maryanne - 2 months ago 12
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="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?

max max
Answer

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

Comments