jQuery scrollTo & localscroll Tutorial

This is an updated version of the localscroll tutorial I wrote a year ago. I hope you find it helpful. If you have any questions, please write them in the comments below and I’ll try to help you :)

In this tutorial you’ll learn how to make anchor links that scrolls the page smoothly using jQuery, scrollTo and localScroll.

Here’s a demo of what the end result will be.

Start with an empty html file. Give it any name you want, as long as it ends with .html or .htm.

Double click the code window to make the code easier to copy.


	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

	<title>My jQuery scrollTo & localscroll Demo</title>

</head>

<body>

</body>
</html>

Inside the head tags we will have to load jQuery, scrollTo and localscroll. It’s important to do it in the order I just wrote. Since scrollTo and localscroll are plugins of jQuery, they first need jQuery to be loaded for them to work.

Copy this code into your head tag of your html document.

<!-- Load jQuery -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

	<!-- Load ScrollTo --><script type="text/javascript" src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>

	<!-- Load LocalScroll -->
<script type="text/javascript" src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>

We’re now loading jQuery and the plugins directly from google. You can also save them to your computer and load them locally. If you want your html file to work offline, this is a must. Now we’re going to set up links and divs to scroll to. Pase the following into the body tag of your html document.

</pre>
<h3>Links to colored boxes</h3>
<pre>

</pre>
<div id="box-links"><a href="#box1">Link to box #1</a> <a href="#box2">Link to box #2</a> <a href="#box3">Link to box #3</a> <a href="#box4">Link to box #4</a></div>
<pre>

</pre>
<div id="box1" class="box">Box #1</div>
<pre>

</pre>
<div id="box2" class="box">Box #2</div>
<pre>

</pre>
<div id="box3" class="box">Box #3</div>
<pre>

</pre>
<div id="box4" class="box">Box #4</div>
<pre>

Let’s set up the actual script that will enable the smooth scrolling. Paste this code inside your head tag at the very bottom (above “</head>”).

	<!-- javascript that will initiate jQuery and the LocalScroll plugin --><script type="text/javascript">// <![CDATA[
	// When the document is loaded...
    $(document).ready(function()
	{
		// Scroll the whole document
		$('#box-links').localScroll({
		   target:'body'
		});

	});

// ]]></script>

Your document probably looks a bit dull now. Only text. We need some CSS! Put this code in your head tag as well:

<style type="text/css">

	/* CSS for the big boxes */

	.box {
		width: 300px;
		height: 300px;

		color: #fff;
		padding: 10px;

		margin: 100px 0 0 0;
	}

	#box1 {
		margin: 300px 0 0 0;
		background: blue;
	}

	#box2 {
		background: red;
	}

	#box3 {
		background: green;
	}

	#box4 {
		background: gray;
	}

	/* CSS for the small boxes that will scroll inside a div */

	#small-box-container {
		border: 1px solid black;
		padding: 20px;
		width: 300px;
		height: 200px;

		overflow: scroll;
	}

	.small-box {

		color: #fff;
		padding: 10px;

		width: 200px;
		height: 200px;
		margin: 0 0 50px 0;
	}

	#small-box1 {
		background: blue;
	}

	#small-box2 {
		background: red;
	}

	#small-box3 {
		background: green;
	}

	</style>

Now, when you click on a link. Your whole document should smoothly scroll down to a colored box.

Here’s the whole code for the html document. I’ve also added a div where you scroll to boxes inside.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

	<title>jQuery scrollTo & localscroll Demo</title>

	<!-- Load jQuery -->
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

	<!-- Load ScrollTo -->
	<script src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>

	<!-- Load LocalScroll -->
	<script src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>

	<!-- Some CSS -->
	<style type="text/css">

	/* CSS for the big boxes */

	.box {
		width: 300px;
		height: 300px;

		color: #fff;
		padding: 10px;

		margin: 100px 0 0 0;
	}

	#box1 {
		margin: 300px 0 0 0;
		background: blue;
	}

	#box2 {
		background: red;
	}

	#box3 {
		background: green;
	}

	#box4 {
		background: gray;
	}

	/* CSS for the small boxes that will scroll inside a div */

	#small-box-container {
		border: 1px solid black;
		padding: 20px;
		width: 300px;
		height: 200px;

		overflow: scroll;
	}

	.small-box {

		color: #fff;
		padding: 10px;

		width: 200px;
		height: 200px;
		margin: 0 0 50px 0;
	}

	#small-box1 {
		background: blue;
	}

	#small-box2 {
		background: red;
	}

	#small-box3 {
		background: green;
	}

	</style>

	<!-- javascript that will initiate jQuery and the LocalScroll plugin -->
	<script>

	// When the document is loaded...
    $(document).ready(function()
	{
		// Scroll the whole document
		$('#box-links').localScroll({
		   target:'body'
		});

		// Scroll the content inside the #scroll-container div
		$('#small-box-links').localScroll({
		   target:'#small-box-container'
		});

	});
    </script>

</head>

<body>

<h1>A very simple jQuery LocalScroll Demo</h1>

<h3>Scroll inside a div</h3>

<div id="small-box-links">

	<a href="#small-box1">Link to small-box #1</a>
	<a href="#small-box2">Link to small-box #2</a>
	<a href="#small-box3">Link to small-box #3</a>

</div>

<div id="small-box-container">
	<div id="small-box1" class="small-box">Small-Box #1</div>
	<div id="small-box2" class="small-box">Small-Box #2</div>
	<div id="small-box3" class="small-box">Small-Box #3</div>
</div>

<hr>

<h3>Links to colored boxes</h3>

<div id="box-links">

	<a href="#box1">Link to box #1</a>
	<a href="#box2">Link to box #2</a>
	<a href="#box3">Link to box #3</a>
	<a href="#box4">Link to box #4</a>

</div>

<div id="box1" class="box">Box #1</div>
<div id="box2" class="box">Box #2</div>
<div id="box3" class="box">Box #3</div>
<div id="box4" class="box">Box #4</div>

</body>
</html>

I hope you found this tutorial useful. If you have trouble getting it to work, please write your questions in the comments below. Cheers!

This entry was posted in Development and tagged , , , . Bookmark the permalink.

72 Responses to jQuery scrollTo & localscroll Tutorial

  1. Kathryn Q. says:

    OH my god, you are the best! Thank you for being so clear and specific! LOVE LOVE LOVE!

  2. Alexa says:

    Hey,

    I’m hoping you get this before my website’s due date! I’ve been trying to implement Fleser’s local scroll for some time now. Came across your tutorial- it’s awesome and seems simple, but the plugin just won’t work for my site. I followed everything step by step… jQuery is working on my page. I’ll write back with the html if you’re free to help.

    Thanks!!
    Alexa

    • adriantomic says:

      Please upload the HTML on http://pastebin.com/ or upload/link it on your drop box. It would be best if you could put it on a server :)

      • Alexa says:

        Thanks so much for the response! I’ve listed my site this time. I can also upload my html and css to pastebin. I think the problem has something to do with the other plugin on my site, but am not sure.. Again, thanks for taking the time to look at this! it’s very much appreciated!!

        • adriantomic says:

          Hi!

          You are loading jQuery twice. Look in your

          after this code:

          Regarding the localscroll script. I can see that the about-link is working, but not the work-link.

          You have do not have any anchor named #workbox, that is why the work-link doesn’t scroll when you click it.

          • Alexa says:

            Yeah, i’ve been able to make the links jump to the anchors just fine. But they aren’t “scrolling”. Just wondering if I need to tweak the settings? I’m looking for that speed that you have on your page.

  3. alex raad says:

    Hello,superb tutorial !

    I would like to know how apply localscroll to other divs,not only to the box-links div.
    Sorry if it´s a nob question

    Thanks a lot

    • adriantomic says:

      Thank you! :)

      If you want to use localscroll on other divs, you just change the target container id to whatever container you’d like to have scroll in. If you want to scroll multiple containers, you have to repeat the code, but with different target id’s. If that doesn’t answer your question, please send me a better description of what you want to do. I might be able to give you a better example.

  4. Caley says:

    This is a great tutorial! Unfortunately, I can’t get it to work though. I copied the code exactly, but it is treating the boxes as anchor links, when I click a link it just jumps to the correct box, I’m not seeing any animation. Any idea what is wrong? Here’s the link:

    http://www.nickandcalea.com/text/index.html

    Thanks!

  5. Chris says:

    Hi Adrian,

    I am trying to get the plugin to work so that when a page is loaded that has a #id at the end, it loads the page then smooth scrolls down to it, rather than just loading the page already at the anchor point. From what I gather it can be done using localScroll, but I just can’t seem to work out how to do it.

    Any help would be greatly appreciated.

    Cheers

    Chris

    • adriantomic says:

      Hello Chris!

      You might not need localscroll for this. Try:

      $('html,body').animate({scrollTop: $("#elementid").offset().top},'slow');

      When the above code runs. It will scroll the page to the element with the id of #elementid.

      Hope it works. Cheers!

      • Chris says:

        Hi Andrew,

        Thanks for your reply.

        What you have suggested does work, sort of. What I am trying to do is have a drop down menu so you can select a sub section of a page from anywhere on the site, and it would load the page, then smooth scroll down to that anchor. However what currently happens is it just jumps straight to the anchor. What you have suggested requires an ID to be defined on the load of each page, which is unknown as the user could click any link from anywhere.

        Any ideas?

        Cheers

        Chris

        • adriantomic says:

          Ok, I think I understand what you want to do.

          You need to get the anchor from the url. When a user clicks the drop down menu, the browser will go to an URL like this: http://www.test.com/#anchor.
          So you need to get the #anchor and animate to it when the page loads.

          Use window.location.hash to get the anchor hash.

          You can try it out and see if it works like this: alert(window.location.hash);

          Store the hash in a variable. Use the earlier code I posted to scroll to the variable which has stored the hasch.

          Something like this:


          // Get the current hash of the page and store it in a variable
          var currentHash = window.location.hash;

          // Scroll down to the current hash using the variable we just created
          $('html,body').animate({scrollTop: $(currentHash).offset().top},'slow');

          • Chris says:

            You have it spot on what I am trying to achieve, and what you have suggested is what I thought might work, however it would seem that the default action of the browser to take you straight to the anchor link overwrites the script, so that when you click the link, it loads the page directly at the section that has the anchor.

            Ill have a play around see if I can solve it, but any ideas would be appreciated.

            Cheers

            Chris

          • adriantomic says:

            I guess you need to prevent the default behavior of the browser to scroll down to the anchor. I’ve only found this solution when googling. http://stackoverflow.com/questions/703530/prevent-stop-auto-anchor-link-from-occurring

            BTW, Stackoverflow.com is a great resource for questions regarding programming (especially jQuery).

  6. Scott says:

    Nevermind!
    I needed the easing plugin.

  7. Scott says:

    Adrian,
    It seems when i plug in options like axis, duration, and queue they work fine. Does easing work or am I just specifying the option wrong?
    Thanks in advance!

  8. INS says:

    Hi
    I’ve been trying to implement localScroll for ages, and I can’t seem to make it work :|
    -
    It works fine if I want to scroll the whole page, but i DONT :]
    I just want to scroll divs inside #okvirCONTENT (so the page stays centered on the screen while the content DIV-s scroll :| …I’m not kidding – I’ve been trying to do this for months :/
    please help:::
    here is the link –>http://dl.dropbox.com/u/7166661/insWins/index4.html

    • adriantomic says:

      Hello!

      If I understand you correctly, you want the page content to scroll inside a div. Set #okvir to overflow: auto;
      In the javascript set the target: #okvir. Set axis to x.

      Not sure if this works, but you might be able to go from here. Good luck!

  9. Struggling says:

    Tried everything….quadruple checked everything….no scroll……any help that can be given I would greatly appreciate?!?!

    • adriantomic says:

      I need some more specificts. Does jQuery load in your site. Write an alert("Working!"); in your javascript file to check if jQuery is loaded. Use developer tools in Chrome or the Firebug extension to Firefox to see if there are any javscript errors.

  10. stefan says:

    Thanks for the tutorial.
    Is there a way to scroll in both directions, horizontal and vertical ?

  11. srsly thanks says:

    Seriously, thanks. It really surprises me that there isn’t a tutorial like this on the ScrollTo / LocalScroll homepage.

  12. Abdulla says:

    Hi guys this is regarding to local scroll problem. I am using separate div for navigation and content div

  13. Don’t know if my reply didn’t appear because my original comment was awaiting moderation or not, so just trying again. Sorry for spamming up your comment feed!

  14. Hi Adrian!

    First of all, thank you so much for this tutorial. I’m just starting out in web design and i was really struggling with this jquery library until i found this clear explanation!

    However, i’m having trouble getting it to scroll horizontally. I was pulling my hair out for ages, but now i’m accepting defeat and turning to a pro! The page in question is here

    I have got it working vertically, but due to the links being at the bottom of the page, it looks a little awkward. I wanted to have them slide from off the page (so they dont just appear from an invisible line) but no matter what i tried it wouldn’t work. Any ideas?

    Thanks in advance,

    Rob

    • adriantomic says:

      I’m glad you like my tutorial :)

      I visited your site. Looks good! If you want the site to scroll horizontally, you first need to place the (.box) div’s horizontally. Change the width of the #content div to something like 4000px. Now you’ll see that the .box divs are side by side.
      Now for the javascript. I think you need to specify which axis to scroll. Since we want to scroll horizontally the axis is “x”. So just add axis: ‘x’ to your localscroll options. Like this:

      $(‘#links’).localScroll({
                 target:’#content’,
      axis:’x’
              });

      Hope it works now :)

      • I tried this before, but it doesn’t seem to work. I’ve updated the css and html like you said and put it online, but the div’s just sit there. The links won’t make it scroll along :(

      • Nevermind, i had to change the target to ‘#container’, just have to muck about with the css to get it to look right now.

        Thanks a lot for your help though. Bookmarked your site :D

  15. eric says:

    I was just wondering if you could slow down the speed to make it scroll more smoothly i am working on a project using this and seems to scroll too fast it almost seems like a jump but it isn’t. Any help on this would be greatly appreciated.

    • adriantomic says:

      If the animation is instant, you might have some problem with your code. If it’s too fast, you might want to change the speed of the animation. The setting is duration: and the time value is in microseconds. So if you want the scroll duration to be 2 seconds, put duration: 2000.

      • eric says:

        Hi Adrian, sorry for the late response but thanks for your help, I really appreciate it. I tried to implement what you said into my code but I cannot figure out where to put the line “duration: 2000″ on. It works fine without the extra line although its still too fast for what I’m trying to do. So when I put the duration line I put it in the only place I could think of which was underneath the “target: ‘body’” line. The problem is when I do, the script doesn’t work anymore and just jumps to the anchor. I’m not sure where that line is supposed to go because I don’t see any other place to put it… or maybe I’m not looking hard enough. If you could show me where or how to insert the line it would help me a lot and finally put an end to my dilemma. (I’ve been on and off on this for a week) Thanks again in advance for your help.

        • adriantomic says:

          I think you might have forgotten to put a comma after the target line.

          Try this code (change the settings so it works on your site):

          $(‘body’).localScroll({
          target: ‘#content’,
          duration: 2000
          });

          If it doesn’t work. Please post a link to your code. You can put the code on pastebin.com. Cheers!

          • eric says:

            Oh man… I tried it with a semicolon but it was supposed to be a comma… I don’t know why I didn’t try that. Programming was never a strong point for me as you can probably tell. I inserted the comma and everything works as I needed it to. Thanks again for taking the time to help. You helped me out BIG TIME. I’m bookmarking your site for future reference. Thanks Again!

  16. Not Offline says:

    This is definitely a more ‘dumb guys’ guide to localscroll which this dumb guy was able to utilize. thanks :)

  17. Francois says:

    Adrian, thanks for the script.
    I wonder if it’s possible not having a height for #small-box-container and having the small-box always scroll to the top of #small-box-container.
    Now if you don’t define a height for #small-box-container it’s not “working”.
    Regards, Francois

  18. Josef Renner says:

    Thanks a lot for your tutorial, this was a big help! I didn’t understand a thing in the original scrollto documentation :-(

  19. Kyle says:

    I have created the following page http://kylehouston.com/testing/localscroll/ where I have a number of main links and then sublinks for these. At the moment when a main link is clicked the content scrolls vertically and when a sublink is clicked eg Blue Inner Link 1 the content slides horizontally.

    My question is how can I update the script so that when I click a main link the content scrolls horizontally and when I click a sublink the content scrolls vertically?

    Thanks Kyle

    • adriantomic says:

      If you are using scrollTo. Set the axis to X (for horizontal scrolling) or Y for vertical scrolling.

      $(...).scrollTo( 'li:eq(15)', 1000, {axis:'x'} );//only scroll on this axis (can be x, y, xy or yx)

  20. He he he, I found the problem: the notorious “hash: true” in the jscript was treating the element as it would a window.

    I changed it to “false”. I should have read the manuals in depth before screaming.
    Thanks a lot.

  21. Good tutorial. I seem to be having a slight problem though. I use the localto, targeting a div, every animation works fine, but it moves the whole page a nudge to the top, like the old fashioned #top.

    Any help..?

  22. Erin says:

    Does this work for diagonal scrolling as well like in the bottom example?

    I’m new to this – sorry if it’s an obvious question! :)

    Example of nav style I’m trying to get: http://www.yourauxiliary.com/

  23. Erin says:

    Hey Adrian thanks for this. Is this jq customizable to make diagonal scrolls like this site below? Click ‘About’ to see what I mean…

    http://www.yourauxiliary.com/

    thank you! Erin

    • adriantomic says:

      Yes, jquery ScrollTo can also scroll diagonaly (the closest distance from A to B). Check out the demo here

      I’m thinking of putting up a new tutorial showing some of the more advanced things you can do with the jQuery scrollto plugin.

      • Erin says:

        Awesome – thanks! yeah that would be amazing… in the meantime I am going to try to nut it out :)

        Cheers
        Erin

        • adriantomic says:

          I’ve done a quick demo for the future tutorial on scrolling x and y with jquery scrollTo.
          http://www.adriantomic.se/scrollTo/

          Things are a bit different this time. I am using scrollTo instead of localScroll to scroll to the divs. I’ve set up a click function for the links. I’ve commented the code so I hope that helps.

          • Erin says:

            Heya – thanks so much for this. On that link though they seem to jump from one box to the other rather than scroll… could that be my computer?…

          • adriantomic says:

            Hmm, that’s weird. I double checked the code and I can’t seem to find any errors. It works for me. Try reloading the page a few times. Please try again: http://www.adriantomic.se/scrollto/

          • Erin says:

            so weird, it’s still jumping. I quit firefox and tried reloading, also emptied cache? strange… I will try it on a computer at uni when I get there today. thanks so much for your help!

          • adriantomic says:

            Do you still have the problem with it jumping? I’ve tried the demo on my friends computer, and it works fine.

  24. Sarah says:

    I think you’re having issues with your code snippets. It’s displaying a large gray box instead of code (FF and Chrome).

  25. Scribbly says:

    I’m to use localScroll to scroll to a specified anchor on load, therefore in the onload function.

    I’m struggling…

  26. umb says:

    hi m8, i just included the js files into the html but nothing happens.
    i just put two links on a page and it doesn’t scroll between. what i’m missing? :(

  27. vinod says:

    Thanks mate,

    just what I wanted.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>