Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Scroll to in jquery? Anyone got any advice.

Hi, I have not played with much jquery before and I am trying to find the simple why of include a smooth scroll with an Anchor Tag. Can anyone recommend how I can do this really simply, as I new to implementing jquery?

thanks

James

3 Answers

I got this from [css-tricks](//css-tricks.com/snippets/jquery/smooth-scrolling/). Chris's example didn't work for me, I found it in the comments!

$('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
        || location.hostname == this.hostname) {

        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
           if (target.length) {
             $('html,body').animate({
                 scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    }
});

EDIT: I changed the * to ^ and ' to " and tidied it a little bit

$("a[href^=#]:not([href=#])").click(function() {
    if (location.pathname.replace(/^\//,"") == this.pathname.replace(/^\//,"") || location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $("[name=" + this.hash.slice(1) + "]");
        if ( target.length ) {
            $("html, body").animate({ scrollTop: target.offset().top }, 1000);
            return false;
        }
    }
});

nice. where do you put the #div for the scroll to know where to go. Am still very new to javascript

thanks for your help much appreciated

Just put the link as usual:

<a href="#id-name">Go to #id-name</a>

The jQuery checks if an <a> tag was clicked.