Reputation: 43
I'm new to Javascript and using Jquery and I ran into a problem. I made a scroll-to-top button which should be visible when you start scrolling down. I got it to work, when I click it I smoothly scroll to the top and when you're at the top it disappears. Only when I first load the page it's already visible, then when I scroll down it briefly disapears untill I reach the point where the element is located and it pops up again when you scroll down even more. Here is my code:
$(document).ready(function(){
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('#backTop a').fadeIn();
}
else {
$('#backTop a').fadeOut();
}
});
$('#backTop a').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
});
Upvotes: 4
Views: 1430
Reputation: 51
You'll also need to change the CSS of the button. By default, the element would be shown after all the elements before it in the HTML are displayed. You can change the CSS to ensure the element sticks to the bottom of the viewport always:
#backTop a{
position: fixed;
display: none;
bottom: 10px;
right: 10px;
}
Fixed positioning ensures that your div always stays at the same position. You can place the element by using the top, right, left and bottom rules. I've set the display to none because initially the back-to-top button should not be visible.
Upvotes: 1