Adding a fixed "back to top" link on every page of your website
Occasionally I get asked how to do the fixed "back to top" button in the lower right corner of my site on every page. This is very simple with PHP/CSS.
First you need to add a class to your stylesheet, this class will fix the image position in the bottom right;
.toplink {
position: fixed;
bottom: 5px;
right: 5px;
}
You can play around with those numbers to position it exactly where you like. Now you need to add the top link, just below the opening <body> tag, put this in;
<a name="top"></a>
Now you need to add the image link, because we're fixing the position with CSS, you can really put this just about anywhere, but I stick it below the footer in it's own div so it will always show below all other content just in case. If you're using sNews, put this in the index.php file before the closing body tag;
<div> <a href="<?php echo $_SERVER['REQUEST_URI']; ?>#top"><img src="images/arrow-up.png" class="toplink" alt="Back to top" title="Back to top" /></a> </div>
WARNING, make sure you properly sanitize the $_SERVER['REQUEST_URI'] variable, such as with the cleanXSS function if you're using sNews, i.e.
cleanXSS($_SERVER['REQUEST_URI']);
Now you just need to put the arrow-up.png image in your images folder and that's it, here are a few samples I just made, feel free to use them if you like.
Now you have a "back to top" link at the corner on every page, placed in the best position for quick access via your user's mouse pointer.



Comments
RSS Comments Feed
slemborg
but didn't really like it, so thanks again for sharring.
Matt
Not sure if you were trying to post some javascript there as an example, but sNews eats anything in tags, as you may already know :)
slemborg
Matt
slemborg
jesth
Usefull stuff, been trying to make one myself, however, went back to this one, and it's working nicely, I just have a few things, I never liked the #top in the link, how would I be able to make a back to top link, without it showing the http://mysite.com/#top ?
Matt
You can change "top" to something else, but it has to be something with a unique id, but the hash indicates it's within the same page, so you can't really get rid of it.
jesth
and changed <body> to <body id="top"> which validates in strict.
Matej