Traditionally, I think a lot of people use a named Anchor tag to create a "Back To Top" page anchor:
I know that I've done that. But, it always felt a bit ganky to me. I mean, the first element in your page is a useless link? That just feels wrong, doesn't it?
Just recently, I found out that you can refer to element IDs rather than named anchors to create page anchors links. This is a really cool piece of information that can easily be applied to the "Back to Top" page anchor links. Now, instead of having these silly, useless links, we can put an ID in the XHTML BODY tag and then use that as our back to top target:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Body ID For Top Anchor Demo</title> </head> <!-- NOTICE: ID in Body Tag. --> <body id="top"> <h1> This Is My Demo </h1> <p style="margin-bottom: 3000px ;"> This paragraph has a huge ass bottom margin so that the page will definitely scoll and put the following link below the page fold. </p> <p> <!-- This link will jump back up to the ID:top in the document. Since that is the ID of the body tag, this link will jump to the top of the page. --> <a href="#top">Back To Top</a> </p> </body> </html>
As you can see here, our XHTML BODY tag as the ID "top." Then, our link at the bottom of the document uses a hash that points to that ID. Clicking on it will act in the same way as a named anchor tag would have, scrolling the user back up to the top of the page. The only minor note here is that the scrolling takes body margins into account. Meaning, if your body has a 10 pixel top margin, the window will jump to a 10 pixel offset since technically, the body is not at the zero offset.
Anyway, this just occurred to me last night and I think it results in much cleaner, more syntactically informative mark-up.
Want to use code from this post? Check out the license.