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.

53 Responses to jQuery scrollTo & localscroll Tutorial

  1. 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!

  2. 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.

  3. stefan says:

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

  4. srsly thanks says:

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

  5. Abdulla says:

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

  6. 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!

  7. 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

  8. 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!

  9. Not Offline says:

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

  10. 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

  11. 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 :-(

  12. 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)

  13. 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.

  14. 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..?

  15. 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/

  16. 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.

  17. 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).

  18. Scribbly says:

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

    I’m struggling…

  19. 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? :(

  20. 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>