Scroll effect with local anchors – Jquery

I forgot where i got this idea of this script, but i remember this is not my own.

About the script:
This is to make some scroll effect inside a page anchors to target  (like #content). Click Here For The DEMO

How to use:
Simply add this scroll.js script with jquery. Set the anchor tags which want to use the effect class=”scroll”


HTML file:


TEST

<div align="center">
<table border="1" cellspacing="1" width="500" id="table1">
<tr>
<td>
<div align="left" id="top">
<table border="0" cellpadding="0" cellspacing="0" width="100" id="table2">
<tr>
<td><a href="#home" class="scroll">HOME</a></td>
</tr>
<tr>
<td><a href="#about" class="scroll">ABOUT</a></td>
</tr>
<tr>
<td><a href="#contact" class="scroll">CONTACT</a></td>
</tr>
</table>
</div></td>
</tr>
<tr>
<td height="500" valign="top"><span id="home">HOME AREA</span>
			<a href="#top" class="scroll">Go Top</a></td>
</tr>
<tr>
<td valign="top" height="700"><span id="about">ABOUT AREA</span>
			<a href="#top" class="scroll">Go Top</a></td>
</tr>
<tr>
<td valign="top" height="800"><span id="contact">CONTACT AREA </span>
			<a href="#top" class="scroll">Go Top</a></td>
</tr>
</table>
</div>

scroll.js script:

$(document).ready(function(){
	$(".scroll").click(function(event){
		//prevent the default action for the click event
		event.preventDefault();

		//get the full url - like mysitecom/index.htm#home
		var full_url = this.href;

		//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
		var parts = full_url.split("#");
		var trgt = parts[1];

		//get the top offset of the target anchor
		var target_offset = $("#"+trgt).offset();
		var target_top = target_offset.top;

		//goto that anchor by setting the body scroll top to anchor top
		$('html, body').animate({scrollTop:target_top}, 500);
	});
});

——————————–

Updated from post discussion:
From Kasper’s Comment

$(document).ready(function(){
  $(".scroll").click(function(event){
    event.preventDefault();
    var offset = $($(this).attr('href')).offset().top;
    $('html, body').animate({scrollTop:offset}, 500);
  });
});
This entry was posted in Jquery, Tutorial and tagged , . Bookmark the permalink.

80 Responses to Scroll effect with local anchors – Jquery

  1. Hi, interesting post. I have been thinking about this topic,so thanks for writing. I will probably be coming back to your site. Keep up great writing

  2. Mohamed says:

    great post ,, many thanks

  3. Mayor says:

    am having problems implementing localscroll…could you give me a hadnnd?

    I got all the file and linked them in my page so whats the next step?

    Thanks

  4. Ray says:

    Is there a way to delay the scroll effect so it does not scroll so quickly?

  5. Will says:

    Hi, Im having issues with my links only scrolling up… I have links at the top of the page that I would like to scroll down to the anchor, but as of now, they will only scroll up.. any thoughts? Thanks!

  6. Kyle Hinton says:

    Is there a way implement this scroll effect after loading an url. I have an anchor hash after my url but it just loads the page, instantly on my hash. I’m wondering if there’s a way to:
    Click link – loads the url
    scrolls down to the hash on the new page

    Is something like this possible? A delay in the scroll, only after the page has loaded, or an auto scroll to hash effect?

    Thank you

  7. sarah says:

    thanks so much for this easy to follow post! however i have one question: i have my site set up in a long horizontal div… with the navigation in a seperate div on the left hand side… when i click and go to the anchor, and the page scrolls to the top, i want the overflow to be hidden on the top and bottom with no scroll bar and my navigation to remain on the side…

    does this make sense?? can you give me any suggestions?

    thanks!

  8. Andre says:

    Hi, first off get plugin. But I’m having problems with targeting a specific area. Heres an example of my markup.

    Contact

    back to top

    Scroll.js will go to the contact area of my page, but I want it to move further down. I’ve been fiddling around with it but can’t seem to get it to work.

    I figured out a way to get the javascript to move into the position that I want. Giving each span# a css position: relative and adjusting the top attribute allows me to let the scroll function exactly where I want it to.

  9. Jason says:

    I just added this to a FAQ page in a WordPress site. Very cool stuff.

    WordPress-specific:
    1. You must use ‘jQuery’ instead of ‘$’
    2. If using Thesis theme, you must add it to the custom_functions.js file. http://www.customizethesis.com/adding-custom-javascript/

  10. stefano says:

    there is a problem…the scroll horizontal doesn’ work….

  11. jimmy says:

    Any way to alter this to work within a container div?? I have buttons in one DIV and images in another DIV.

  12. zeally7 says:

    You save my life!
    Thank you.

  13. Pingback: kndesign.com.ar » Blog Archive » efectos jquery para tener a mano

  14. Pingback: Links of the Week: April 23rd | Bainbridge Studios

  15. Taila says:

    thank you so much!
    great post!

  16. TheMeekon says:

    Nice i have already implimented this is several things i was working on in School

  17. Leandro Alves says:

    works perfectly!!!
    Thanks

  18. Phil_M says:

    Hi, thank you for the great tutorial!

    I have only one question. Is it possible to set the duration of the scroll effect?
    I don’t know javascript.

    thanks again

  19. NMynarcik says:

    This doesn’t seem to work for me in IE.

    Anyone else get this to work in IE? (IE8 tested, no success)

  20. Because it works in Opera shakes the screen?

  21. Avery says:

    Thank you very much for this wonderful snippet. I’ve implemented it onto my website (a small sign up link on the bottom of the page) and it works perfectly. There aren’t many elegant and simple solutions for a smooth scroll and your solution is one of them!

  22. Just wanted to say thank you! I was searching for smooth scrolling solutions, and yours was by far the easiest to understand for a beginner like me. I’ve bookmarked your site for future reference, thanks so much!

  23. kaiwalya r. says:

    Thanks,
    its nice,
    but instead of table can’t we use div there??

  24. Pingback: 2010 review – Pagination and anchor scroll are most wanted | Beschi's Works

  25. Russ says:

    Lovely! So simple to get it working. Exactly what I was looking for. Thank you.

  26. Pingback: Man! Week 5 was AWESOME! « ART342~W11

  27. bab says:

    Yosh,

    i’m a designer and i want to learn about jquery…i’m sorry i am so baaaaaaaaaaad at coding ..the fact is you gave us the code HTML with JS i think i have to place the .js code inside right??After i went to the jquery website and try to download it, but it give me code that i don’t know what to do with!!

    but i really don’t know..please can you give me a file with everything inside , i think it’s gonna be easier for me to learn, i’m so lost with everything.
    Looks so simple for you but honestly for me it’s a headheache!!LOL

    Thank you very much.

  28. v0lZy says:

    The code above is great, but it has a drawback in a scenario where you put your navigation links in one div and scroll a separate div in such a setup, that both divs are always on screen (the scrolling of the content in the second div does not move the links).

    In such a situation, if you click the same link on the left twice in a row, the script scrolls slightly off…

    Id like to thank people at ##javascript on freenode, in particularly ‘very’ for a solution and ‘pigdude’ for his time in trying.

    The modified code:

    // initialize lasttrgt variable (we will need this to check if the link was already clicked)
    var lasttrgt;

    $(document).ready(function(){
    $(“.scroll”).click(function(event){
    //prevent the default action for the click event
    event.preventDefault();

    //get the full url – like mysitecom/index.htm#home
    var full_url = this.href;

    //split the url by # and get the anchor target name – home in mysitecom/index.htm#home
    var parts = full_url.split(“#”);
    var trgt = parts[1];

    //check if the target link was previously a target (this would mean that the link was clicked before)
    if (trgt!==lasttrgt) lasttrgt=trgt; else return;

    //get the top offset of the target anchor
    var target_offset = $(“#”+trgt).offset();
    var target_top = target_offset.top;

    //goto that anchor by setting the body scroll top to anchor top
    $(‘#content_field_right’).animate({scrollTop:target_top}, 300);
    });
    });

    • Beschi says:

      Hi v0lZy,
      thanks for your comments.
      All my codes are some basic examples – how to use JQuery for various purpose. Hope somebody will extend the basic and do good.

      Hope your comments will help someone to understand a little bit more. :)

    • cady says:

      Hello, I tried the original script and it worked perfectly; and I tried this edited script to move just a div, and it didn’t work… any ideas what I could be doing wrong? all I did was swap scripts.

  29. v0lZy says:

    An additional modification that solves some issues with refreshing in the case described in my previous post above. Big thanks to ‘very’ again, i take no credit.

    (just replace #content_field_right with the div you want to scroll)

    // initialize lasttrgt variable (we will need this to check if the link was already clicked)
    var lasttrgt;

    $(document).ready(function(){
    //scroll to top when the page is loaded or refreshe
    $(‘#content_field_right’).scrollTop(0);

    $(“.scroll”).click(function(event){
    //prevent the default action for the click event
    event.preventDefault();

    //get the full url – like mysitecom/index.htm#home
    var full_url = this.href;

    //split the url by # and get the anchor target name – home in mysitecom/index.htm#home
    var parts = full_url.split(“#”);
    var trgt = parts[1];

    //check if the target link was previously a target (this would mean that the link was clicked before)
    if (trgt!==lasttrgt) lasttrgt=trgt; else return;

    //get the top offset of the target anchor
    var target_offset = $(“#”+trgt).offset();
    var target_top = target_offset.top;

    //goto that anchor by setting the body scroll top to anchor top
    $(‘#content_field_right’).animate({scrollTop:target_top}, 300);
    });
    });

  30. v0lZy says:

    An even better version …

    // initialize lasttrgt variable (we will need this to check if the link was already clicked)
    var lasttrgt;

    $(document).ready(function(){
    //scroll to top when the page is loaded or refreshe
    $(‘#content_field_right’).scrollTop(0);

    $(“.scroll”).click(function(event){
    //prevent the default action for the click event
    event.preventDefault();

    //get the full url – like mysitecom/index.htm#home
    var full_url = this.href;

    //split the url by # and get the anchor target name – home in mysitecom/index.htm#home
    var parts = full_url.split(“#”);
    var trgt = parts[1];

    //check if the target link was previously a target (this would mean that the link was clicked before)
    if (trgt!==lasttrgt) lasttrgt=trgt; else return;

    //get the top offset of the target anchor
    var target_offset = $(“#”+trgt).position();
    var target_top = target_offset.top + $(‘#content_field_right’).scrollTop();

    //go to that anchor by setting the element scroll top to anchor top
    $(‘#content_field_right’).animate({scrollTop:target_top}, 300);
    });
    });

  31. Kasper says:

    Your code could be a lot shorter, it’s useless to get the anchor name from the url since you can get it from the href attribute.


    $(".scroll").click(function(event){

    event.preventDefault();

    var offset = $($(this).attr('href')).offset().top;

    $('html, body').animate({scrollTop:offset}, 500);

    });

    • Beschi says:

      Hi Kasper,
      Nice try. But $(this).attr(‘href’) – will return a value, not will be a selector for an element. So this won’t work.
      Have you tried?

      Thanks for your comment. I will try to short the code.

      • Beschi says:

        OR simply,
        we can write like this,

        event.preventDefault();
        var offset = ($("#"+$(this).attr('href').split('#')[1]).offset().top);
        $('html, body').animate({scrollTop:offset}, 500);

      • Kasper says:

        Hey Beschi, yes I have tried. And I know $(this).attr(‘href’) returns a value, that’s why you have to use $($(this).attr(‘href’))

      • Beschi says:

        Sorry Kasper,
        I have tested.
        Works great.
        Thanks. :)

  32. Michael says:

    I found a great page that give numerous downloadable examples of how to change the text inside an anchor using jQuery. They are really helpful for web 2.0 and web 3.0 sites.

    http://www.ajaxera.com/jquery-change-text-in-anchor/

  33. Alessandro says:

    Hi!
    Thank you so much for this scroll effect, really useful!

    I don’t know why but since some days it doesn’t work anymore on my website.
    I didn’t change anything but now there is no scroll effect on my links…

    Can you help me?
    You can check this on http://www.menomysofa.com/vers3
    Every link on the website should work…

  34. Vince says:

    Great trick Beschi! I’ve used it a few times already.
    I’ve looked through the posts and didn’t see any reference to this, but I’m trying to combine this with another effect that requires the anchor ID to be in the URL, like index.htm#about.
    Any thoughts on how to achieve this?

  35. Worked first time! Thank you very much!
    Sanj

  36. juliograffin says:

    THAAAAAAAAAAANNNNNKSSSSSSSSSSSS A LOOOOOOOOTTTTT!!!!! =)

  37. I’m having trouble implementing this with WordPress. Is there anything special that I have to do? I have the scroll.js and jquery-1.2.6.min.js in a folder named js in the current theme folder, and I called both of them in the header.php before the body tag.

    I saw earlier a comment saying something about $ being replaced for wordpress, but I didn’t understand what the user meant.

    Any help would be greatly appreciated.
    Thanks!

  38. Buchhandlung Dortmund says:

    http://www.buchhandlung-arnold.de Very nice blog dude! How do u get so much visitors? My blog is very sad – only 10 visitors per day. Btw: Nice article!

  39. pixot says:

    http://www.pixotdesign.com
    Pixot is a web design company. We specialize in design for a web application, web startups and e-commerce. We provide high quality web designs based on usability rules. We can guarantee unique designs at a competitive price. If you are launching a new business and you need an unique website design this solution is the best for you.

  40. Giulio says:

    this is a great feature that I really thought all browsers would have built-in by now. it always bugged me that anchors jump you around with no reference of where you went or how you got there… (I thought at least Chrome would have it…) until then, this js is perfect, thanks

  41. mantis569 says:

    Thanks for this, useful little bit of script :)

  42. J says:

    I had issues with this scrolling to random locations when the page was scrolled. I also added a backscroll amount (anchor_height) to keep an adjacent element visible. Here’s my fixed version:

    $(“.scroll”).click(function(event){
    //prevent the default action for the click event
    event.preventDefault();

    //get the full url – like mysitecom/index.htm#home
    var full_url = this.href;

    //split the url by # and get the anchor target name – home in mysitecom/index.htm#home
    var parts = full_url.split(“#”);
    var trgt = parts[1];

    //get container offset
    var container = $(‘div.list_container’);
    var container_offset = container.offset();
    var window_offset = $(window).scrollTop();

    var anchor_height = $(‘.chart_nav_anchor_line’).height();

    //get the top offset of the target anchor
    var target_offset = $(“#”+trgt).offset();
    var target_top = target_offset.top – container_offset.top – anchor_height + container.scrollTop();

    //goto that anchor by setting the body scroll top to anchor top
    $(‘div.list_container’).animate({scrollTop:target_top}, 500);
    });

  43. The demo appears to be protected? I get a “Authentication required” pop up.

  44. Worked a charm, small footprint and functional. Thanks dude.

  45. Aaron says:

    Looks like your demo and download no longer working?

  46. Ben says:

    That’s not really the most effecient way to do this, I’ve managed to strip out 3 lines of code and make it more jQuery friendly. Also this code works with standard page anchor markup.

    $(document).ready(function(){
    $(“.scroll”).click(function(event){
    // Prevent the default action for the click event
    event.preventDefault();

    // Use the jQuery object to get the href attribute instead.
    var parts = $(this).attr(‘href’).split(“#”);

    // Work out the top of the target anchor (minusing 20 to show 20 pixels above the anchor for aesthetic reasons
    var target_top = $(‘a[name=’ + parts[1] + ‘]’).offset().top – 20;

    $(‘html, body’).animate({scrollTop:target_top}, 1200);
    });
    });

  47. Mark says:

    Hi, how do i implement the html code to index.php? help. :(

  48. @@@ says:

    When someone writes an paragraph he/she maintains the thought of a user in his/her brain that how a user can understand it.
    Thus that’s why this paragraph is perfect. Thanks!

  49. Dan says:

    Did you have any luck getting this scroll effect working when clicking an anchor from a different page? I noticed you were going to have a go a couple of years back, so any update on this would be VERY useful. Thanks

  50. omer says:

    demo is fucked up

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s