www.LondonsWebDesign.com

 Home  Design  Development  Analysis  Blog  About Us  Contact Us



There are 4 comments for this article.
Add to the discussion.

Please feel free to about this article.

Use jQuery and CSS to Create
a Persistent "Return to Top" Button

Take a look at the lower-right corner of the browser and you'll see a small yellow button that reads TOP. When you scroll the web page down to read more of this web design&development how-to blog article, that button will stay fixed in position. Once you have scrolled down, clicking that button will immediately return you to the top of the document. That button, and its behaviour, is exactly what this article is all about.

There are a number of components involved in this technique. Of course a little HTML will be needed. In this case very little as only one line of HTML is needed to display the button on the web page. That one line of HTML will, more importantly, also assign the button's content (in this case the word "TOP"). Along with the HTML some CSS will be needed. This in the form of a class and a psuedo class. And, finally, a couple of jQuery functions will be needed.

The HTML

The HTML required for this return to top button is minimal. All that is needed is the following line:

<div class="backToTopButton"><strong>TOP</strong></div>

The line above uses an HTML div tag along with a strong tag. The div tag assigns the class option to enable the CSS (Cascading Style Sheet), described in the next section, to style the button. It's in the CSS that the button's foreground color for the button's text and the background color for the button's color, and more, will be set. The strong tag simply makes the button's text bold.

Because the CSS for the div tag will cause the button to be positioned absolutely, this line of HTML code can be placed pretty much anywhere between the opening and closing body tags. I chose to place the line just above the closing body tag. It's out of the way there and it seems right for it to be at the bottom of the document, as it will be displayed at the bottom of the document in the browser window.

The CSS

The CSS used for creating the button is a little more involved than the HTML, but it's not too painful. Here's the CSS code:

<style>
div.backToTopButton {
     font-family: Georgia;
     font-size: 12px;

     color: #000000;
     background-color: #fffa70;

     padding: 3px 10px 20px 10px;
     width:50px;
     text-align: center;

     border-width : thin thin thin thin;
     border-color : #000000 #000000 #000000 #000000;
     border-style : solid solid solid solid;
     border-collapse : collapse;

     -moz-border-radius: 10px;
     border-radius: 10px;

     position: fixed;
     bottom: -20px;
     right: 10px;

     z-index: 200;
}

div.backToTopButton:hover {
     color: #ffffff;
     background-color: #1574e9;

     cursor: pointer;
     cursor: hand;
     }
</style>

The Class

The first section of the CSS class "backToTopButton" assigns the font-family and sets the font-size to be used for the button. The second section sets the text color to black and the background color to a yellow that fits with the current page design on this web site. You may want to change these values to reflect the fonts and color scheme of your own web site.

The third and fourth sections draw a border and define some extra padding around the text. The width and the padding values can also be changed depending on your needs and the text you want to use for your button.

Defining the space and drawing the border creates the button shape/background. Creating the button in this manner means that no graphics are used at all. Pretty cool, eh? Of course this leaves open the possibility for differences in the final appearance of the button, depending on the browser used. For example, the fifth section defines rounded corners for the button. These two lines work for Mozilla's FireFox and Google's Chrome, respectively. Unfortunately, there is no Microsoft Internet Explorer compatible solution without the use of graphics, so IE users will see a rectangle button with square corners. Everything else will still work correctly, though.

After defining the rounded corners the final statements in the class lock the button's position in the lower-right corner of the browser window using the "position: fixed;" statement. The bottom and right options are also set using values that will place the button in the lower-right corner of the browser window.

Note how a negative value is used in the "bottom" option. I could just as easily have set the value to zero and changed the round-corner settings to apply only to the top corners, and not assigned a bottom border, but I chose to use these values finding it took a little less coding and playing around to get right. Play around with the values yourself to see what effect they have on the placement of the button. The "right" value of 10px (pixels) was chosen to keep the button close to the right edge of the browser window. Again, this value can be changed to suite your needs. In fact, I have used a similar technique to create a login button to be placed in the upper-right corner of the screen (use top and right), and, as another example, using left: 10px; would move the button to the bottom-left of the screen 10 pixels from the left side of the browser window.

The final line of the "backToTopButton" class sets the z-index to 200. Any value above 1 will normally work, but I already have other objects occupying various z-index spaces on this web page, and I wanted to be sure the button would float above any of those objects. The z-index basically works like layers with objects having higher values appearing above objects with lower values. Note that negative values can also be used. Typing "CSS z-index" into Google will yield links to tons of resources that will explain the z-index in more detail.

The Hover Psuedo Class

To make the button interactive it would be cool if you could change the color so that the user would know that it is indeed a button. The CSS pseudo-class "hover" is just what's needed.

The backToTopButton:hover pseudo class changes the color of the text to white, changes the background color to a shade of blue and, more importantly, it changes the mouse-pointer to a hand when the mouse-pointer is moved over the button. The two lines "cursor: pointer;" and "cursor: hand;" are included to assure compatibility with different browsers.

Note that the CSS needs to be placed between <style> tags or called as an external file in the head section of your HTML document.

The jQuery

And last, but not least, the jQuery. All that needs to be done in the script is to attach a click event to the button. Doing so will mean that that an action (returning to the top of the document, in this case) can be caused to take place when the button is clicked.

Here's the code:

     <!-- Activate the "Return to Top" button -->
     <script language="JavaScript">

          $(document).ready(function(){

               $("div.backToTopButton").click(function() {
                    $(window).scrollTop(0);
               });

          });
     </script>


The first line in the script uses the $ (dollar sign) jQuery shortcut. The $ character is basically a shortcut that stands for jQuery. So the first line is a line of jQuery code that waits for the document to be ready i.e. the web page is fully loaded. It then runs a function. That function attaches the click event for the button to a second function.

The second function waits for a mouse click to happen with the mouse over the button created by the one line of HTML and the CSS described earlier. So what happens when the "button" is clicked? The final line of code scrolls the window, or the document, back to the top of the browser by setting window.scrollTop() to a value of zero.

Note that running this script requires that you also run one of the versions of jQuery. This particular script was tested with jQuery versions 1.4.x and 1.5.x.

To add the jQuery library to your web page, you'll need to include a line similar to the following in your HTML document:

<script language="JavaScript" src="scripts/jquery-1.4.3.min.js"></script>

The line above refers to where, and which jQuery version you would have installed. So, for example, the line above refers to jQuery version 1.4.3.min which is stored in the subfolder scripts. If you're new to jQuery you can find out more about this JavaScript Library at jQuery.com. Be aware that the call to jQuery should appear on your web page before the jQuery functions described in this article.

Also note that using different DOCTYPE tags in your HTML may have a profound effect on how the different browsers display the button. The code seems to run as expected with a DOCTYPE of HTML 4 strict:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

And with HTML 5 DOCTYPE tags, as well:

<!DOCTYPE HTML>

What? No JavaScript?

If you're worried about what will happen if your visitor has JavaScript turned off you can simply wrap the HTML div tag in a script wrapper, like so:

<script language="javascript">
     document.write('<div class="loginButton"> <strong>TOP</strong> </div>');
</script>


Using the JavaScript document.write method to create the div tag and its contents will mean that... No JavaScript, no div tag... No div tag, no button... No button, no worries.

I've tested this code with three of the current major browsers: Microsoft's Internet Explorer 8, (Note the IE link will take you to the IE 9 page as Microsoft is rolling out their new browser at the time of this writing) FireFox 3.x and Goggle's Chrome 9.x.

Update

Thanks to @vertstudios on Twitter and his reply to my tweet about this article, here's another cool jQuery effect that can be substituted for the rather jarring scrollTop(0).

Substitute the following script for the script above and the document will scroll slowly towards the top of the browser window rather than moving there all at once.

<!-- Activate the "Return to Top" button -->
<script language="JavaScript">
$(document).ready(function() {
     $('div.backToTopButton').click(function(){
          $('html, body').animate({scrollTop:0}, 'slow');
     });
});
</script>


The new code shown above still uses the scrollTop(); method but it adds a 'slow' animation to it.

Here's the original link to this code snippet on Snipplr.com that @vertstudios sent me.

If you enjoyed this web development article, or have a question or comment about it please use the form below to add to the conversation.


article by: Michael Clark for www.LondonsWebDesign.com
created on: February 23, 2011

About the Author, Michael Clark

After writing, teaching and lecturing about the Internet and the Web for over 15 years, Michael recently decided to get back to his software development roots.

Michael's company, www.LondonsWebDesign.com, designs and develops web sites for small and medium-sized businesses in and around the London, Ontario, area.

When he's not helping his clients 'get the Web,' Michael is hard at work developing a mini-CMS that can be easily customized for each of his client's websites. You can 'follow' Michael on Twitter as @LondonWebDev. Just look for the icon of the guy tugging on his ear :).


There are 4 comments for this article

   .          .          .          .          .          .          .          .          .          .          .          .

On May 4, 2011 at 1:43 pm  Beal wrote...


I like this solution a lot! Thanks very much for sharing!

   .          .          .          .          .          .          .          .          .          .          .          .

On May 4, 2011 at 4:47 pm  Michael wrote...


Hey Beal.

Thank you for your comment. I'll be writing more jQuery articles, so stay tuned.

   .          .          .          .          .          .          .          .          .          .          .          .

On June 26, 2011 at 7:59 am  Christopher Young wrote...


Very good.. clear instructions...thanks

   .          .          .          .          .          .          .          .          .          .          .          .

On June 27, 2011 at 4:11 pm  Michael wrote...


Hi Christopher.

Thanks for stopping by and for leaving a comment. Stay tuned for more jQuery articles.

-Michael

   .          .          .          .          .          .          .          .          .          .          .          .

Add your comment to the discussion

*Name:*Email:
Your Website's URL
(eg. www.LondonsWebDesign.com)
*Your Comment:
*All fields are required. Your email is required but will never be displayed.

Some other articles you may like:





Please feel free to about this article.


Become a Fan of ours on Facebook and Follow us on Twitter.
The following links are to businesses and organizations that we deal with in and around London, Ontario:




HomeDesignDevelopmentAnalysisBlogAbout UsContact Us

Web Design and Hosting by www.LondonsWebDesign.comCopyright © 2010 - 2014
Web Graphics and Photos by www.grafx-design.comRead our privacy policy

Home
New to LondonsWebDesign.com? This is a good place to start.
Web Site Design
Read about our web design philosophy and take a look at some of our work.
Web Site Development
SEO, Social Media and more... Let us help you build your business on the Web.
Web Site Analysis
See how we can help you develop a presence on the Web.
Do It Yourself
If you feel like creating your own website design or tackling the development of your own web presence, then you might be interested in our series of articles - a 'blog, if you will, - about how-to Web whatever.
All About LondonsWebDesign.com
Everything you wanted to know about LondonsWebDesign, but were afraid to ask. Find the answers to questions like "Who's in charge around here, anyways?"
Contact LondonsWebDesign.com
Use our handy email form to send us comments or questions.
  Use this form to send us an Email
Your name:
Your email address:
Corfirm your email address:
The subject:
Your email message:
Follow Us on Twitter
Follow Us on Facebook

TOP