Fluid Anchors – Smooth Anchors Using MooTools

By  on  

While we as programmers get more used to using AJAX and advanced JavaScript frameworks, we can only assume that our users will. At one time, it was acceptable to have elements dynamically just "pop into" the screen but now we must strive to make the experience smoother for our users. That's why MooTools has put a big focus on the "Fx" part of their framework.

Page anchors are great. Page anchors allow us to link within the same page and this is especially useful for long pages where we can use a "top" anchor to move to the top of the page, saving the user miles of scrolling. The only problem with this functionality is that it is extremely jumpy; the user could click the anchor and be placed to the anchor point before they know what hit them. Not smooth.

MooTools provides an easy, customizable plugin to fix the chaos of anchors.

The Files

MooTools SmoothScroll Minimum Requirements (~19kb)
XHTML Working Example

The Code

window.addEvent('domready',function() { new SmoothScroll({ duration: 1800 }); });

The Usage

The only adjustment to your anchors is that you will need to add an id attribute to the anchor that mimics the same value as the name element.

<a title="sugar" name="sugar" id="sugar"></a>
<h1>Sugar!</h1>

You'll not that the option I've used about is the duration option, which essentially sets the duration of the scroll. SmoothScroll calculates the amount of space on the page between the anchor link and the anchor and speeds the scroll automatically so that all scrolls take the 'duration' time to complete.

Another unobtrusive usage of the MooTools JavaScript framework to improve the functionality of your pages.

Recent Features

  • By
    CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

  • By
    Detect DOM Node Insertions with JavaScript and CSS Animations

    I work with an awesome cast of developers at Mozilla, and one of them in Daniel Buchner. Daniel's shared with me an awesome strategy for detecting when nodes have been injected into a parent node without using the deprecated DOM Events API.

Incredible Demos

Discussion

  1. Great use of mootools! Any idea how you could get this to work on page load?

    i.e. example.com/index.php?page=this#anchor

  2. Joshua: Great question! I don’t know of a way to achieve this. I’ll look into this a bit more. I’m not sure if there’s a way to negate the browser’s functionality to go down so we can implement our own.

  3. I was playing around with this a bit last night. Im not sure if its possible to bypass the browsers initial recognition of the anchor, but it should be possible to load the anchor with js and php.

    So instead of having a link like:
    ?page=this#anchor

    using one like:
    ?page=this&anchor=that

    then in the head of a page, creating some php and js
    if ($_GET[‘anchor’] !=””){
    some JS to load anchor
    }

    Now what that js should be Im not sure yet. Back in the day there were some autoclick functions but those have been phased out.

  4. @Josh: Got you now. I think the JS should be something like:

    var myFx = new Fx.Scroll('myElement', {
        duration: 2000, //2 seconds
        wait: false
    }).toElement('element_id');
    

    The above javascript code is Moo 1.2.

  5. Oops — try this instead:

    var myFx = new Fx.Scroll(window).toElement('myElement');
    
  6. Great job David! It seems to works perfectly.

  7. id lve to use this but including the .js file breaks my slider:

    Accessible News Slider: A jQuery Plugin
    http://www.reindel.com/accessible_news_slider/

  8. Hello.

    I’m a beginner with Javascript and Mootools and your site is perfect for a guy like me :-)

    I’d like users to scroll down to the bottom of a page, and there, a hidden ‘div’ should now be visible.
    How can I get a page to scroll and simultaneously toggle a div property ?

    Thanks

  9. @Thomas: I believe you can add an “onComplete” to the scroll.

  10. Thanks for this quick answer, but I don’t know how to do that… Isn’t it possible to launch two scripts at at the same time ?

  11. Lee

    I am working on an anchor at the moment in JS, but i only want it to work when the page becomes scrollable.

    How do i do this?

    In other words, when the text can all fit on one web page browser i want the anchor to not work, but when they page becomes longer by the user adding data to it via a shopping cart function i want the anchor to work for reference purposes.

  12. Lee: That’s a tough task. I don’t have a any ideas right away. Anyone else?

  13. ADI

    First off, thanks for sharing.

    Seems to be working perfectly in both IE and Firefox.

    Safari doesn’t seem to be friends with the script unfortunately.

    If I click the ‘sugar’ link there is a 1 or 2 second pause, then a direct jump to the sugar section.

    In my own site there is another strange behaviour with Safari.

    Any ‘next’ link will smoothscroll to the top of the page (opposite direction) and then jump directly to the anchor location (where it was supposed to scroll to in the first place).

    Anyone else experiencing weird behaviour in Safari or know how to fix this?

  14. Dan

    Seems very jumpy in Safari 3.1.2 for me. Delay in the scrolling then jumps to the anchor. Any fixes?

  15. It doesn’t work on Opera

  16. Are you using a doctype?

  17. tstorm

    Yeah. This one: !DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd”

  18. @tstorm: Can you provide an example URL?

  19. Sure. This site is a mess cuz I’m using it for css experimentation, but here it is: http://wiscostorm.net/stories/

  20. @tstorm: The “sidebar” element is outside the HTML element, which could be the problem.

  21. Miguel

    This is an amazing site and thanks for the mootools help! I was about to quit on mootools but then I found your site and tutorials and they really help! Guys like you make the internet what it is today.

  22. @Miguel: I really appreciate that comment. I’ll keep striving to make Moo life easier for everyone!

  23. tstorm

    I fixed that sidebar thing. Thanks.

    Unfortunately, I’m still having problems getting it to work. Kind of a mystery, eh?

    I appreciate the help.

  24. @tstorm: You definitely have the path to the smoothscroll.js file wrong. It’s giving a 404 error. That’s a huge problem! :)

  25. tstorm

    Yikes. Alright, let me check that. I deleted and re-uploaded some stuff with a back-to-the-drawing-board mentality, but I must have goofed the path. Thanks.

  26. tstorm

    Woohoo! That did it! Thanks, man.

    Now my question is, if I want the page to load in the middle section — so for instance, if you were to have your sample page load on the “sugar” section of the page — should I use a simple onload goToAnchor js or something else?

    My page is nearing what I’d like it to do, but if I click on any of my categories at the bottom of the page, things are all out of whack.

    I don’t really expect you to answer this one, David, since it’s totally above and beyond the already-above-and-beyond help you’ve been doling out, but in case anyone’s interested in exploring another js dilemma — this one specifically about the interaction between js and a wordpress blog.

    Thanks again!

  27. @tstorm: Have you tried Lim Chee’s solution here?

    http://davidwalsh.name/mootools-onload-smoothscroll

  28. tstorm

    Nice! That’s making my categories work (albeit a little jumpy), but how can I make it so that the page isn’t always loading from the top down? On my particular site, I want the top of the page and/or the #about anchor (which is close to the top) to remain out of sight unless someone clicks on about.

    But I’m thinking this might get too messy, what with wordpress’s permalinks, pages, and categories. Maybe I need to think about some other workarounds.

  29. Miguel

    Hey David,

    I have this content inside a div that I have a fixed width and height on. Is there anyway to make this work inside a div?

  30. @Miguel: Take a look at:

    http://docs.mootools.net/Plugins/SmoothScroll

    I think passing the “win” as the second parameter could work — the win being the div element, of course.

  31. Miguel

    This is what I have according to the mootools documents. Excuse my “newb-ness”

    <script type="text/javascript">onComplete.addEvent('domready',function() { new SmoothScroll({ duration: 1800{, win }); });</script>
    
  32. @Miguel: Your syntax looks a bit off. Try:

    <script type="text/javascript">
    window.addEvent('domready',function() { 
        var ss = new SmoothScroll({ duration: 1800}, $('scrollingDiv'));
    });
    </script>
    
  33. Miguel

    Hey David,

    Thanks for the quick responses. I am assuming the $('scrollingDiv') is the name of the div id? Also what is the “$” for? I am not using any backend language.

  34. @Miguel: Yes, the div id should go in the scrollingDiv spot. And the $('') selects that specific DIV element.

  35. Miguel

    For the life of me this is not working. I want it to scroll within the div and not the body of the page. Check it out. http://cm.sirs.com/cms/MLKsmall/index.html

  36. @Miguel: You page is password protected so I can’t look at it. Perhaps the following page would be better:

    http://docs.mootools.net/Plugins/Fx.Scroll

  37. Hey David,

    This works great…except (as with all the other smooth-scrolling scripts I’ve tried) that something in the js interferes with lightbox.js, another script I’m using on my site.

    Could this be a quick fix (renaming something?)?

    Thanks,

    Coleen

  38. @Coleen: Unfortunately there’s no quick fix. Moo and Prototype don’t play nice in the sandbox.

  39. Corey Klemow

    ADI and Dan: Safari sometimes doesn’t like empty anchor tags. Try wrapping the anchor around some text, a graphic, or even just an   – chances are that will clear up your Sarari woes.

    If that solves your problem, then you’re simply running foul of a bug in Safari; it has nothing to do with this keen-o scrolling script. I ran into a similar problem a few months ago when trying to use anchor links to navigate an overflow div.

  40. Corey Klemow

    Whoops, forgot to use code commenting… “some text, a graphic, or even just an &nbsp;” is what it shold say above…

  41. Corey Klemow

    Hi – regarding the code Joshua and David were talking about on April 1 (hmmm… April Fools?) :) …anyway, am I interpreting correctly that the code is meant to allow you to link to an anchor from another page, start by displaying the page’s top, and then, after a pause (2 seconds in the above example), begin to scroll to the selected anchor? If so, I can’t get it to work… I’m still just jumping directly to the anchor as soon as the page loads. I tested in IE7 and Firefox 3. Can one of you please post a link to a working example? Thanks!

  42. Corey Klemow

    Sorry to flood this post with comments, but is it possible for the scrolling action to be triggered if the scrolling page is in an iframe and the link to the anchor is on the parent page?

  43. Hi David,

    thanks for the great tut!
    I have a problem with it – it’s working great, but somehow it kills my jquery contact form…

    can you look at it in your free time please?

    http://www.evidesign.com

    thanks!

  44. false alert…or not that false, but instead of mootools, I used jquery script..
    it’s working now..

    THANKS again :)

  45. Hey David,

    Thanks for this. Its kind of my first foray into js.

    My trouble is that i’m trying to use Lightbox 2 on the same page as the smooth scroll. I actually switched it over to Slimbox in hopes they’d play nicer together since they both use moo as the framework.

    Anyway, they don’t play nicely together. 1 or the other. I’m sure its because they are fighting over the anchor tags. Is there any way to produce harmony between these two?

    THANK YOU SOOOO MUCH!
    Jace

  46. Jim

    I was wondering if there is a fix for the smooth scroller for Opera or Safari. It works great in Firefox, haven’t tested it in IE yet. But I get the same problem as I’ve read before: it pauses for 2 seconds then just jumps to the anchor in Safari and Opera. When I click the link to the “top” it just jumps without the pause. Thanks a lot.

  47. I am having a similar problem using smooth with lightbox, but I noticed on a website I made for a local foundation using the wordpress theme K2, which uses a type of smooth scroll for scanning threw achieve posts, does not interfere with lightbox.

    I don’t know much of anything about javascript beyond using these nifty little plugins, other wise I would dig into it looking for an answer. But I thought maybe someone here would be interested in making these two popular scripts compatible. I would personally appreciate it ;)

  48. Hey thanks Jace Hirschi, I don’t know what you did but I copied and pasted the combined script file from your website and used < div> instead of < a> to set the anchors and everything works fine.

  49. patience

    Thanks for the great examples… I have been searching for atleast a week and a half for this type of example. I found it about 10 hours ago and I have yet to succeed. I have read over everyone’s comments and followed links and suggestions. I am not sure as to what could be the issue for me…Any comments, suggestions, or links to tutorials would be greatly appreciated.

    http://www.annseale.com/v4.html

  50. July

    Regarding question of “how you could get this to work on page load?”. First make anchor invisible, i.e. style=”display:none” – that’s way browser won’t navigate to the anchor on startup :)
    Next, on the onload event repair display property, lets say, to display:block and use SmoothScroll as described :)

  51. Simon

    Hi David

    Thanks for this great script, it is working perfectly just putting a bit of code in the page!

    However, I just noticed a small problem I am facing, on one of my pages I have a tabbed content area, and the script seems to be effecting this aswell (obviously as they are anchors too, #tab1, #tab2 etc).

    Any way to get around this as all these elemnts need an ID?

    Thanks

  52. Jenn

    Great stuff David!

    Thanks for sharing your script with us, I can’t wait to use it!

  53. Hi,

    Can we simultaneously use two modules in .html page? I have successfully implemented “MultiBox” & also “Smooth Anchor” (both uses mootools) on separate .html pages. When both are in same page (MultiBox” & “Smooth Anchor”), MultiBox stops working, where as, Smooth Anchor is working fine.

    Please help me, Thanks in advance.

    Syed Haroon

  54. Cat

    I’d love to see a how-to for setting up a ‘top of page’ just like you’re using currently (The Top Of Page link is only shown once the user scrolls down and then fades away with an animation when back in start position). Can you write one up please? :)

  55. Zimba

    Great unobstrusive script, but how can I get it to scroll until the anchor is at the bottom, instead of the top, of the page ?

    Thanks a lot

  56. I’m trying to get this working and I’m having problems… on the following page…

    http://audiowhispers.org/test/index2.htm

    for some reason it works on the ‘Back to the Top’ links, but when I click on the links to go to each section it seems like it tries to scroll up the way…?

    any help would be appreciated…! I’m a total beginner at this so be gentle..!

  57. Hi David!

    Nice blog you have. Congratulations!
    I´m designing a site in where i use the Smooth Anchors Tool and Lightbox in the same page.

    It seems to be an incompatibility between Smooth Anchors and Lightbox. When i open a gallery in Lightbox and clic on “next pic” or “prev pic”, the anchors roll :S

    Is there any solution for this? I hope you can find it.

    Thanks!
    Carlos

    PS: Sorry for my english.

  58. Hey David,
    What are the chances I can use this on a horizontal page, between anchors? I’m very new. I appropriate your site a lot.

  59. Colin

    appreciate! sorry, and thanks

  60. @Syed Haroon: If anyone is having problems working this with MultiBox, or another script, this one doesn’t conflict.

    http://webdesignandsuch.com/2009/11/using-smooth-scroll-with-page-anchors-and-javascript/

  61. David… I wish I saw this single line of code 24hrs ago! Brilliant, thank you :)

  62. davide

    I have just try it in wordpress.

    In my template I have separated page header.php and footer.php
    in header I have put the script code in the head tags

    I have put the id link code in the body tags

    and in the footer page, I have put the link to refer #id

    But I can’t see the animation! ther is a skip from link to id, but without scroll!

    I have done more test, in a simple page html put in there the 3 elements and it works!
    How is possible in wordpress no?

    thanks for reply.
    Davide

  63. robert

    Hey David,

    I love smoothscroll! Which browsers is this compatible with?

  64. I wanted to use SmoothScroll and simpleSlide on my new web page. But there is some kind of conflict. Did someone found soluion for that problem?

  65. Patrickv

    I’m trying to implement this (any many others) but it doesn’t work. I mean it does, it “jumps” to the respective section but it doesn’t “scroll”. What could be the issue ? do I need a real testing server ? because right now i’m on localhost. many thanks man

  66. I’m trying to implement this (any many others) but it doesn’t work. I mean it does, it “jumps” to the respective section but it doesn’t “scroll”. What could be the issue ?

  67. Sebastian

    I’d like to smooth-scroll inside a overflow-x div. Is this possible? I guess I have to change “window”, but I don’t know what to.
    Can you help, please?

  68. chris

    brilliant!!!!!!!!!!!!!!! thanks so muchly!!

  69. Ann

    Hi-

    Will this only work if the page is .php? it doesn’t seem to work on my index.html page?

  70. Igor

    This will work in Android?

  71. Guys,

    Please help me. I am trying to create a page for a friend, and I haven´t done this in ages, really ages.

    There is something wrong and I cannot find it. The scrolling works in IE and Firefox but not in Chrome and Safari. I do something terrible wrong and I cannot find the error.

    If some of you could help me I would really apreciate it.

    Thanks a lot

    Daniel

  72. Robert

    Is there an easier implementation of this, like say, a plugin that would enable us to use it on WordPress with ease?

  73. Kuldeep

    You’ll not that the option I’ve used about is the

    Should be

    You’ll note that the option I’ve used about is the

  74. Hi, Neat post. There is an issue along with your website in internet explorer, might test this?
    IE still is the mzrket leader and a huge element off other folks will pass over your fantasetic writing due to this problem.

  75. What are the chances I can use this on a horizontal page, between anchors?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!