Feb
20

Inspired by others ideas and code and also by the need to insert a Top Link like button on my own website I managed to write a script that not only works on all major browsers but it’s also neat and animated :)

The expected outcome

The general idea was to try and add a link on the right side of the page that will appear and stick there after a  certain percentage of the page is scrolled down and when clicked will smoothly scroll the page back to the top. Also it’s mandatory that this should work on all major browsers (including IE).

Here is an example how this should look like (example working already on this page, just scroll down to see it)

Animated top link Example

The button and the placement problems

In order to add the button to the page we just need to add this code to our page just after the <body> tag:

<a href="#header-top">
<div id="back-top" style="display: block;"></div>
</a>

The DIV tag will be used to show our top link using a background-image (but you can use a text just as well) and the anchor will be used to link us to the top of the page (in this case by the most outer div tag with the #header-top id) .

Now the CSS code to style our Top button should look like this:

#back-top{
 background:transparent url(arrow-up.gif) no-repeat scroll 0 0px;
 display:none;
 text-decoration:none;
 position:fixed;
border:none;
}

So we’ve set a background image that will be seen by the user, in order to get the desired effect and the position of our DIV is FIXED so that will stick in the bottom right corner when scrolling the page. DISPLAY = NONE to hide it until we scroll down inside the page and afterwards show it to the user.

All good now we can say, but after some testing in Internet Explorer we will see that in some versions POSITION:FIXED is not working at all (ex: IE6) or buggy on other versions (ex: IE7). In order to fix this we will have to insert some hacks in our CSS code (I won’t get more into this matter because it will be a really long article but you can search all about it). What we need to do is to add overflow:hidden to the code and this will be the easiest way to solve position problems that we may encounter, now the CSS code should look like this:

#back-top{
 background:transparent url(arrow-up.gif) no-repeat scroll 0 0px;
 display:none;
 text-decoration:none;
 position:fixed;
 bottom:10px;
 right:10px;
 overflow:hidden;
 border:none;
 text-indent:-999px;
 height:32px;
 width:42px;
}

Now that our button is inserted to the page and styled to appear on the right side  we can go further with some mouse over css code and the java-script that will animate the button.

The mouse over css code could be like the one bellow. I just practically used a sprite image to show the default and hover effect of our button.

#back-top:hover{
 background-position:0 -32px;
 display:block;
 overflow:hidden;
}

Code used for the Top Link show / hide effect

The main idea is to bind the scroll event of the page and when a certain percent is scrolled down we just show the button to the user. If the user scrolls back to the top we need to hide the button once again. I used jQuery to do this and turned out in the process to be a plugin so we can use it wherever we want.

The plugin function will take 3 parameters:

  • tag object of the button – the DIV used to show or hide the top link button (passed as the selector)
  • min – Amount of pixels from the top needed to show the button
  • fadeSpeed – The speed of the fade in / fade out effect set in milliseconds

We first declare the settings and the default values for each of them:

jQuery.fn.topLink = function(settings) {
 settings = jQuery.extend({
 min: 1,
 fadeSpeed: 200,
 ieOffset: 50 //used to properly calculate the height in IE
 }, settings);

Then we listen for the scroll event and we check the height from the top until it gets bigger then our min value, in witch point we show our button using the fade in effect. If the height from the top is smaller then our min value we will hide our button in the same manner.

 return this.each(function() {
 //Listen for scroll
 var el = $(this);
 el.css('display','none'); //in case the user forgot
 $(window).scroll(function() {
 if(!jQuery.support.hrefNormalized) {
 el.css({
 'position': 'absolute',
 'top': $(window).scrollTop() + $(window).height() - settings.ieOffset
 });
 }
 if($(window).scrollTop() >= settings.min)
 { el.fadeIn(settings.fadeSpeed); }
 else
 { el.fadeOut(settings.fadeSpeed); }
 });
 });
};

The jQuery.support.hrefNormalized means that using the jQuery features we are trying to detect browser features. The support object contains boolean flags and was added just for this purpose to write code using browser feature detection. Because IE has a different mode to handle the href attribute (it returns the full URL instead of the exact href attribute) I used .hrefNormalized to see if the code is executing in IE or not and if it does using css we are setting the top property every time the users scrolls the page, assuring us in this way that the position of our button remains constant without flickering or any other bugs we may encounter with different browsers.

Final code used to show / hide our button

The full code of our jQuery plugin should look like this:

jQuery.fn.topLink = function(settings) {
 settings = jQuery.extend({
 min: 1,
 fadeSpeed: 200,
 ieOffset: 50
 }, settings);
 return this.each(function() {
 //Listen for scroll
 var el = $(this);
 el.css('display','none'); //in case the user forgot
 $(window).scroll(function() {
 if(!jQuery.support.hrefNormalized) {
 el.css({
 'position': 'absolute',
 'top': $(window).scrollTop() + $(window).height() - settings.ieOffset
 });
 }
 if($(window).scrollTop() >= settings.min)
 { el.fadeIn(settings.fadeSpeed); }
 else
 { el.fadeOut(settings.fadeSpeed); }
 });
 });
};

Now in order to use the plugin using a separate js file (or in what way you may like) we add the code to our page and then we just call it when the dom is ready or at the end of the page right before the </body> tag:

// Go to Top Link
$('#back-top').topLink({
 min: 800,
 fadeSpeed: 500
});

According to our settings above the go to top button will appear after at least 800 pixels will be scrolled down from the page and the effect will be completed in half of a second. After the page scrolls back to top the code is executed again and the button will hide again because our min value is not reached.

Smooth scrolling all anchor links inside your page

For the smooth scroll effect I used another plugin made by Karl Swedberg that you can get from Github here. In order to use it just load the js file to your page and add the following code.

// All anchor tags will be bind to smooth scroll in page
$('a').smoothScroll();

Now all anchor tags inside your page will be smoothly scrolled when clicked. For example the Go to Comments link inside your blog, or any other anchor that points somewhere inside your current page will have this nice effect.

Final considerations

I’ve checked the code in FF 2.0 +, IE 7+, Opera 10, Safari 4 and Chrome 5 and works well on all of them. If anyone finds a version that breaks or is buggy just let me know and perhaps we could fix it. This article is not meant to be a tutorial for all users and some or more programming skills are required in order to integrate the code in your HTML pages but you don’t have to alter anything to it it works as it is. Hope you will find it useful and give feedback if you have some.

If you like this post, share it with your friends!

You can leave a response, or trackback from your own site.

13 Responses to “Animated Top Link that works on every browser”

 
  1. **Juanito** says:

    Awesome!
    I try this in my WordPress sandbox but doesn’t work :( (for me)
    I am ultra newbie in javascript and coding (php) and I would like implement this hack in my blog.
    I don’t know what Im doing wrong, please help me.
    I leave the code of my header.php file http://tinypaste.com/948a1 if you want to take a look.
    Thanks a lot.

    • Radu says:

      I real can help you if I can’t see the demo for myself, but for what I can determine from your header file is that you execute the code before the DOM loads completely so try to add it like this:

      $(document).ready(function(){
        // Go to Top Link
        $('#back-top').topLink({
        min: 800,
        fadeSpeed: 500
        });
      
        //smoothscroll
        $('a').smoothScroll();
      });
      

      And try again … hope this helps.

  2. NetKit says:

    Nice work. I wish I stumbled upon this earlier. :)

    • Radu says:

      Thanks :) I appreciate. I see that you updated your site with something like this, it’s real nice and great job with all your posts, they are real helpful.

  3. Ryan says:

    I am currently developing a site for my employer and this tutorial was exactly what I was looking for.

    However, I do have a question. This works flawlessly in all browsers with the exception of IE. As I scroll down the page the fixed div flickers. Do you know of anyway to counteract this?

    • Radu says:

      Hello Ryan glad you found this useful :) As for the IE problem I really need to see an example and for you to tell me what version of IE are you using.

  4. Mirko says:

    Hi Radu,

    I’m working on a static XHTML website and I’ve got some problem about the script. It’s all OK, but the jQuery function “Go to the top” don’t work.
    I’ve copied all codes in a separated JS file and inserted before the tag the “// Go to Top Link” code.

    I’ve tried to manipulate and adjust the codes but nothing… so, can you help me?

    Thank you,
    Mirko

  5. Amit Wadhwa says:

    I used your code but the top link does not work and also the image stays on the page – what have I done wrong? Am using WP 3.0.1

  6. Amit Wadhwa says:

    OK I have got the links to work but I can not get the smooth scroll to work. The fade in and out are not working either – Can you please help:)

  7. Amit Wadhwa says:

    I have the code implemented on http://www.premiumpower.ie/safety – my up arrow just stays at the bottom right corner of the screen – while that is not a huge issue, it is annoying that I could not get the code to work:)

 

Leave a Reply