I have a smooth solution in two ways: smooth scrolling and a smooth button.
With JavaScript disabled, it´s just a link on the bottom of the page to the anchor top
.
(#
as href can be pretty unstable.)
With JavaScript enabled:
- Hide the div containing the link (to avoid flickering).
- Fix the position of the div at the bottom right border of the window.
- Remove the
href
attribute and add click
handler for smooth scrolling.
(keeps URL and browser history tidy and I need no return
or preventDefault
in the scrolling function)
- Fade div in / out depending on scroll position:
Display link only if scroll position > window height.
- Update the position on resize.
HTML
<body>
<a name="top"></a>
...
<div id="scrolltotop" style="display:block;text-align:right">
<a href="#top" title="scroll to top"><img src="scrolltotop.png" alt="scroll to top"></a>
</div>
</body>
jQuery
function scrolltotop_display()
{
var el=$('#scrolltotop');
if((window.pageYOffset||document.documentElement.scrollTop)>window.innerHeight)
{ if(!el.is(':visible')) { el.stop(true, true).fadeIn(); } }
else { if(!el.is(':animated')) { el.stop(true, true).fadeOut(); }}
}
function scrolltotop_position()
{
var el=$('#scrolltotop');
el.css('top', window.innerHeight-100);
el.css('left', window.innerWidth-100);
scrolltotop_display();
}
$(window).on('load', function(){
$('#scrolltotop').css('display', 'none');
$('#scrollToTop').css('position', 'fixed');
scrolltotop_position();
$('#scrollToTop a').removeAttr('href');
$('#scrollToTop a').on('click', function(){$('html, body').animate({scrollTop:0}, 500);});
});
$(window).on('scroll', scrolltotop_display);
$(window).on('resize', scrolltotop_position);
#go-to-top
is an element ID, which must be unique. Callingeach
on something that should only contain one element may work, but is naughty. Probably you want to give your elements a class instead, and select with$('.go-to-top')
– Maltreat