MooTools onLoad SmoothScrolling

By  on  

SmoothScroll is a fantastic MooTools plugin but smooth scrolling only occurs when the anchor is on the same page. Making SmoothScroll work across pages is as easy as a few extra line of MooTools and a querystring variable.

The MooTools / PHP

//once the DOM is ready...
window.addEvent('domready', function() { 
	//smooooooth scrolling enabled
	new SmoothScroll({ duration:700 }, window); 
});

<?php if($_GET['scrollto']) { ?>
//once the window has loaded...
window.addEvent('load', function() {
	//scroll down to the specific spot
	var scroll = new Fx.Scroll(window, { wait: false, duration: 2500, transition: Fx.Transitions.Quad.easeInOut });
	scroll.toElement('<?php echo $_GET['scrollto']; ?>');
});
<?php } ?>

Of course, this is a system you would only want to implement on a small site with few anchors.

Recent Features

  • By
    5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our .js files and our .css, but...

  • By
    5 HTML5 APIs You Didn&#8217;t Know Existed

    When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature...

Incredible Demos

  • By
    HTML5&#8217;s placeholder Attribute

    HTML5 has introduced many features to the browser;  some HTML-based, some in the form of JavaScript APIs, but all of them useful.  One of my favorites if the introduction of the placeholder attribute to INPUT elements.  The placeholder attribute shows text in a field until the...

  • By
    Full Width Textareas

    Working with textarea widths can be painful if you want the textarea to span 100% width.  Why painful?  Because if the textarea's containing element has padding, your "width:100%" textarea will likely stretch outside of the parent container -- a frustrating prospect to say the least.  Luckily...

Discussion

  1. Nice, but actually, this can be done without PHP. By simply using the URL hash, this can be done better:

    window.addEvent('domready', function(e) {
    	var el = window.location.hash.substring(1); // the hash
    	if(el){
    		window.scrollTo(0,0);
    		var scroll = new Fx.Scroll(window, { wait: false, duration: 2500, transition: Fx.Transitions.Quad.easeInOut });
    		scroll.toElement(el);
    	}else
    		new SmoothScroll({ duration:700 }, window);
    });
    
  2. @Lim Chee Aug: Cool, I’ll test that out!

  3. Oh ya, ignore the ‘else’ and the ‘e’ parameter in my code. Was typing too fast :P

  4. Nice david !
    But the page is reload :S
    It is the only lacking, but otherwise there was no other choice.

  5. @Catar4x: I think the page reload is the whole point of this script. It’s showing you how to make the smoothscroll effect when the page reloads. David Walsh made a tutorial previously on how to smoothscroll without reloading the page. You can read that at this link: http://davidwalsh.name/smoothscroll-mootools-12

  6. Johan Douma

    Would be good to loop thru each link that links to a named anchor and then change them to have ?scrollto=### in the href.
    If there is already a smoothscrolling script that looped thru the page, the page will not reload when clicked.
    That way search engines will not index the same page with scrollto’s params several times.

  7. Chris Martin

    @Josh: The main reason to use Lim Chee’s method rather than the PHP-based solution using GET is that it ensures that the anchor links retain their functionality when JS is disabled (the anchor links in the PHP version do nothing without JS).

    With Lim Chee’s, without JS you get old school anchor links, but with JS if you navigate directly to a page with a # in the URL, it will automatically SmoothScroll you down to it once the page has loaded. It’s a great example of progressive enhancement! :)

    The full code:

    window.addEvent('domready', function() {   
      new SmoothScroll({ duration:700 }, window);
      var el = window.location.hash.substring(1); // the hash
      if(el) {
        window.scrollTo(0,0);
        var scroll = new Fx.Scroll(window, { wait: false, duration: 700, transition: Fx.Transitions.Quad.easeInOut });
        scroll.toElement(el);
      }
    });
    
  8. Eric

    Doesn’t scroll to top?

  9. I like using this method: using ? instead oh hash stops the page jumping around etc.

         var scroll = new Fx.Scroll(window, { wait: false, duration: 2500, 
         transition: Fx.Transitions.Quad.easeInOut });
    
                      var loc = document.location.href;
    
                      var splitLoc = loc.split("?");
    
                       if(splitLoc[1]){
                        var to = splitLoc[1]
                        scroll.toElement(to);
                      }
    

    with the url being http://www.rickyh.co.uk/barwick/site/services.php?RCIS and RCIS is the id of the element.

  10. Johan

    @ Ricky, That’s not the best thing to do concerning SEO. Using ?, you’ll end up with duplicates of your pages in the search engine indexes.

  11. Lukie

    Hi, i cant quite get it. How for example start a new page and force it automaticcly to scroll to let’s say “chapter 4” ( your examples ). And do it on start without any click from he user, this examples are not working for me. Normal smooth scroll works perfectly. If i could just specify one point on the page this would works quite fine. Thx for help ;-) i know its quite noobish question.

  12. Lukie

    Ah sry for double post… it can really be an ugly,, ugly solution like pointing to the page content by pixels or so… :-).

  13. Lukie tr this link see if it works http://www.rickyh.co.uk/barwick/site/services.html?LPSC . I changed the code on the site because its under construction. O and it works by firing the scroll event onDomReady or page load.

  14. I’m only 13 years old and I really don’t know anything about html or java or any other code, but I’m making a website using adobe dreamweaver cs3. I was wondering if anyone would be so kind to make a code for me with a horizontal smoothscroll to a location like x:1000 pixels. Also could you tell me how to activate the code when a button is pressed. I’m willing to make a donation, since I don’t know how much work this is.

  15. @Chris

    this is a cool method, but I’m not sure if it works in webkit. I’m testing on Chrome & Firefox…things work perfectly in FF, but webkit seems to want to go directly to the # on the page immediately.

  16. correction, I had my function attached to a delay method, I took that out and it works…kind of. Its jumps all round the place in webkit.

  17. Hi Great post thanks for sharing. Im giving it a try now.

  18. Thanks so much for this man! You’ve saved me after hours and hours of screwing around.

  19. hi everyone, does anyone please have a sample files of this smooth scroll for php?, i can’t get it to work on load, im using the original php example from david but cant get it to work,

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