jQuery topLink Plugin

Written by David Walsh on March 2, 2009 · 70 Comments

Last week I released a snippet of code for MooTools that allowed you to fade in and out a "to the top" link on any page. Here's how to implement that functionality using jQuery.

The XHTML

<a href="#top" id="top-link">Top of Page</a>

A simple link.

The CSS

#top-link	{ display:none; position:fixed; right:5px; bottom:5px; color:green; font-weight:bold; text-decoration:none; border:1px solid green; background:Lightgreen; padding:10px; }

A little CSS for position and style.

The jQuery JavaScript

//plugin
jQuery.fn.topLink = function(settings) {
	settings = jQuery.extend({
		min: 1,
		fadeSpeed: 200
	}, settings);
	return this.each(function() {
		//listen for scroll
		var el = $(this);
		el.hide(); //in case the user forgot
		$(window).scroll(function() {
			if($(window).scrollTop() >= settings.min)
			{
				el.fadeIn(settings.fadeSpeed);
			}
			else
			{
				el.fadeOut(settings.fadeSpeed);
			}
		});
	});
};

//usage w/ smoothscroll
$(document).ready(function() {
	//set the link
	$('#top-link').topLink({
		min: 400,
		fadeSpeed: 500
	});
	//smoothscroll
	$('#top-link').click(function(e) {
		e.preventDefault();
		$.scrollTo(0,300);
	});
});

You'll see that I've added jQuery's ScrollTo plugin to add some smoothness to the anchor.

Please note that this version doesn't work with Internet Explorer due to IE's lack of CSS "position:fixed" support. Here is a shotty attempt at IE support:

//plugin
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() {
				//stupid IE hack
				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);
				}
			});
		});
	};

Know of a better way to incorporate IE support? Share it!

Comments

  1. Hmm… I thought you can do el.hide() instead of el.css(‘display’,’none’)? :P

  2. Wow, nice plugin, I think I might incorporate this into a website in the not so long future. And good luck with the submission to the JQuery website :)

  3. @Lim Chee Aun: Good call! Updated.

  4. If you use something like this:

    body { overflow: hidden; }
    div.content {
    height: 100%;
    overflow: auto;
    }

    shouldn’t work? I will have to try it :), nice article anyway

  5. It shows up fine but when I click it, it doesn’t scroll. Do you know why this would be?

  6. Hi David! I translate to Turkish and publish to my site. I hope you like it. Here is link -> http://www.kadirgunay.com/jquery-top-link-jquery-yukari-cik-baglantisi.html
    And i added your link bottom of the article :)

    Thank you, and see you

    Kadir,

  7. Nice job David !!

  8. Hi All,
    Nice plugin and really useful. I’ve got a fix for IE7 (need to test ie6 if you care about it)

    Basically I added the last value in the full CSS below *height: 1.5%
    For those who don’t know the hack. The * makes it an IE7 value only (you could use _ for ie6) and FFox ignores it. I don’t think its W3C standards though but it does the job.

    #top-link {
    display: none;
    position:fixed;
    right: 5px;
    bottom: 5px;
    color: #eeefea;
    font-weight: bold;
    text-decoration: none;
    border: 2px solid #1d2835;
    background: #222b3a;
    padding: 6px 10px;
    *height: 1.5%
    }

    As for t the problem of the full script not working. I had a hard time with it too. Copying and pasting the code doesn’t work for some reason so I downloaded the demo example and striped out what I needed and it worked. I hope this was usefull to someone.

  9. Faisal Alim March 3, 2009

    i like it

  10. nice one..surely goin 2 try my hands on it!!

  11. Awesome script David! Implemented it on opensourcereleasefeed.com. Thanks!

  12. I love the solution! Good work!

  13. wow nice , i m going to use it on my blog

  14. I noticed its not working with IE…is there a way to solve it i need it…!

  15. Works for me!

  16. Has anyone yet mentioned today that IE sucks?

  17. David you do not cease to surprise :)

  18. A really amazing idea David, thanks! I made a similar plugin inspired by yours,
    nice work!

  19. @Matt,
    I saw your plugin, looks very good. Can you tell how to use it to scroll to any specific control, rather than to the top of the page.

    In my case, I want to scroll to say my DIV named “header” : <div id=”header”> </div>

    Thanks,
    Pawan

  20. Important thing for a longer post. Thanks. I will publish it in my Bangla blog Bangla Hacks.

  21. Hey David,

    Just wanted to add that this is a fantastic script, many thanks for producing it. I am implementing it slightly differently, without the fixed positioning, so no IE problems so far!

    Many thanks again,

    DanC

  22. nice plugin..
    thanks.. :)

  23. I would like to thank you so much! I have been trying with JS to work this out, with no avail. This helps so much. I even bookmarked your site! (Which for me is a rarity) I will also link you back on my index.

    Thanks again,

    Tm0.

  24. where i must place javascript code for blogger

    example: between or ???

  25. Hey David,

    Happy New Year to you! Just wanted to drop you a quick note about topLink. I have been using it often in my web dev work and really enjoy the usability it adds to sites.

    I actually think all sites should implement some version of back to top and as such I converted your topLink plugin into a Chrome extension ;) https://chrome.google.com/extensions/detail/afpmpmikeidpfnfmnmlpecnoipnnnfmn

  26. I had this working on my site and now I can’t get it to scroll to the top of the page. Does anyone know how to fix this problem?

  27. Thanks for showing us how to make this effect. Nice work!

  28. Do I use both of the provided codes in one .js file to have support in all browsers?

    As you’ve not mentioned how to use it.

    And I’m not sure of javascript just yet.

    Because I already have on of these but it isn’t supported in IE.

    So use both in one .js file? or what to do with the IE fix code?

    Thanks (I’ve subbed to comments).

  29. easy fix for IE8: place the link for ending the and then only make an empty div and in it the link

    example: http://raumausstatter-goetz.de/

  30. Your plugin is awesome! I just would like to divide fading in/out and smooth scrolling into 2 different functions to apply it to my own taste. How should I do that? Can you help me, please? I don’t know JS. :(

  31. Thank you so much for sharing this plugin! =D

  32. I’ve been messing around with this code for a while now, initially it worked straight away. Then on implementing it to my blog http://nicholaswarren.tumblr.com it seemed to not work. It’s only on testing that I realized it does still work in Safari, but not Firefox.
    Now I’ve only recently started to understand jQuery so I’m still not sure how to fix this yet. A bit more tinkering needed, would like to test it in other browsers too.
    Just thought I’d share this with you, in case someone else has had this problem.

  33. John Apachet March 25, 2011

    All works, apart from clicking the button. It doesn’t take you to the top? Any ideas???

  34. Works great but google chrome is spitting out this js console error everytime I click the link:

    Uncaught TypeError: Object function (j,s){return new b.fn.init(j,s)} has no method ‘scrollTo’
    (anonymous function)
    c.event.handle
    c.event.add.h.handle.o

  35. opendoor40 July 25, 2011

    hiya! I really love this, but I’m very new with this kinda code…

    can someone tell me where to add these sections of code? (I’m using Tumblr by the way)

    thanks :)

  36. I was trying to implement this plugin to make it scroll smoothly, but to scroll to the left.

    Firebug was giving a error on $.scrollTo(0,300); function not found
    I’m not a big programmer but I’m been able to solve the problem by using.


    $('#top-link').click(function(e) {
    e.preventDefault();
    $('body,html').animate({scrollLeft:0},800);
    });

    Instead of


    $('#top-link').click(function(e) {
    e.preventDefault();
    $.scrollTo(0,300);
    });

    I have scrollLeft() because thats what i needed but for scroll to the top use scrollTop()
    Hope that this helps someone.

    Cheers and thanks for the plugin

  37. Wonderful feature. Thank you. Will use it on my blog.

  38. Hi,
    Top example, really easy to implement too.

    Also works fine in IE 9, so bonus!
    Shaun

  39. Nice plugin, thanks. If I quickly scroll up and down with the mousewheel, the animation continues. Should I use stop() somewhere to correct this behaviour ? Please advise, thanks!
    -Mark

  40. Great post! But if I quickly use mousewheel to scroll up and down, the animation continues by itself. Can I use stop() somewhere to correct this behaviour? Appart form that, great tutorial, thanks.

  41. Hi,
    how could I use this to scoll to an Anchor?

    BR

  42. Sorry for the tripple post!

  43. Comment this code, and top menu link should work (in Chrome and Ie (windows 7) works and not in firefox):

    //smoothscroll
    /*$(‘#top-link’).click(function(e) {
    e.preventDefault();
    $.scrollTo(0,300);
    });*/

  44. Dear David,

    Happy new year.

    Many thanks for publishing your plugin.

    I publish long text-based web documents for use by my students. In addition to the ‘Top of Page’ link I would also like to add a ‘Bottom of Page’ link so that students can jump straight to the bottom of the page. Also, when the student is mid-page, I’d like both the ‘Top of Page’ and ‘Bottom of Page’ links to be visible. Is there any straightforward way of achieving this using your plugin. I am not a jQuery / Javascript expert so I would be very grateful if you could advise me.

    Second: does your licence allow me to use your plugin on my University’s web site. The pages in which it would be used will be accessible only to students and instructional staff.

    I would be grateful for your responses.

    Many thanks and kind regards,

    Grant Bailey
    University of Western Sydney

    • Hello Grant,

      Per your questions:

      1. A tiny bit of work would need to be done to swap out the link text and href within this block:


      if($(window).scrollTop() >= settings.min) {
      el.fadeIn(settings.fadeSpeed);
      }
      else {
      el.fadeOut(settings.fadeSpeed);
      }

      2. Use it however you’d like!

  45. Very nice, what i was really looking for, let me just place a small image , hope would be perfect. thank you!

  46. Jack Black January 18, 2012

    Awkward on a wide screen monitor though, if the main site is centered at 960px, the “top of page” link appears waaaaay off to the right over there and probably goes un-noticed…

  47. Wow! Really nice plugin! Helps me a lot!

  48. lovely :)
    thank you!

  49. Hi David,
    Latest jQuery 1.8 not working with the topLink.
    Will you make the updates?

  50. Hi David,
    Recently jQuery is updated to v1.8.0.
    My scroll to top button now is not working anymore.
    I also updated jquery.scrollto v1.4.3. It not working either.
    Not sure if you have you encounter this issue.

  51. hy, did some minor changes to the .js code. cause the scrollTop wasn’t working

    			//smoothscroll
    			$('#top-link').click(function(e) {
    				e.preventDefault();
    				$('body,html').animate({scrollTop:0},800);
    			});
    

    hope that helps.

  52. [...] jQuery topLink Plugin [...]

  53. Hey,
    It was realy easy to implement this on my own page. Easy and clear steps :)

    Thank you !

  54. [...] 1. jQuery TopLink Plugin [...]

  55. [...] Walsh stellt auf seinem Blog ein tolles jQuery toplink-Plugin vor. Mit Hilfe des Codes kannst du dir einen Button einrichten, der erst beim Herunterscrollen der [...]

  56. wow brilliant nice work i really appreciate this. keep it up.

  57. [...] jQuery topLink Plugin – MORE INFO [...]

  58. [...] 1. jQuery topLink Plugin [...]

  59. [...] 1. David Walsh’s jQuery topLink Plugin [...]

  60. [...] Scroll to Top、jQuery topLink Plugin、Scroll To Top Plugin、Disappearing “Scroll to top” link with jQuery and CSS、UItoTop jQuery [...]

  61. […] of a good JavaScript-powered enhancement. I've showed you how to accomplish this task using jQuery and MooTools; here's how you can accomplish that same effect using […]

  62. […] topLink es un plugin creado por David Walsh utilizando jQuery. […]

  63. it’s easy to use
    thank you very much

  64. […] bischen html…ein bischen css ein wenig mehr jquery und du hast deinen Top-Button jQuery topLink Plugin Ask not what JTL-community can do for you – ask what you can do for JTL-community […]

Be Heard

Tip: Wrap your code in <pre> tags or link to a GitHub Gist!

Use Code Editor
Older
Backup Your Database into an XML File Using PHP
Newer
Animated AJAX Record Deletion Using jQuery