Picnic Website Code Tutorials

A Better jQuery Back To Top Of Page Tutorial

3/17/2013

View Demo

I needed a fancy "Back to Top of Page" for this website that was simple, functional, and pretty to look at. Considering it's such a small, somewhat insignificant piece, I also could not live with any code that was overly bloated. I couldn't find anything I liked. So I built one. By doing it the way I did it, it also works when JS is off. With JS on it only appears as you scroll down. Currently it appears once you scroll down 100px from the top. This can be changed to whatever value you prefer by changing the number in this bit "scrollTop()>100)" to suit. I also added some fancy CSS3 animation. The anchor with the id of #top is position fixed so it can be placed anywhere. In this case we place it at the top so when JS is off it doubles as the jump to top anchor. It's given display none so it doesn't FOUC via a little piece of JS in the head so it does show when JS is off. I think it turned out very nice. What do you think?

CSS

#top {
width:50px;
height:50px;
position:fixed;
bottom:10px;
right:10px;
border-radius:10px;
box-shadow:0 0 4px #555;
z-index:999;
display:block;
}
.js #top {
display:none;
}
#top b {
position:absolute;
background:rgb(255,255,255) url(../../img/top.png) 11px 14px no-repeat;
background-color:rgba(255,255,255,.6);
transition:all 0.3s ease-in-out;
-webkit-transition:all 0.5s ease-in-out;
width:50px;
height:50px;
border-radius:10px;
}
#top:hover b {
background-color:rgba(255, 255, 255, 1);
background-position:11px 10px;
}
		

HTML

<a href="#" id="top"><b></b></a>
		

JS at the top

<script type="text/javascript">document.documentElement.className = 'js';</script>
		

JS at the bottom

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
// jQuery Back To Top Plugin
$(function(){$(window).scroll(function(){if($(this).scrollTop()>100){$("#top").fadeIn(1000)}else{$("#top").fadeOut(750)}});$("#top").click(function(){$("html, body").animate({scrollTop:0},600);return false})});
</script>
		

Sponsors

Top Donators

Friends of Mine