Mark
Mark

Reputation: 525

editing scrollTop to use href value

I currently have the following code for a certain link on my website to scroll back to the top, but I can't figure out how I can change this to use a specified href value instead of a pixel value. Current script:

$('.scrollToTop').click(function () {
            $('html, body').animate({ scrollTop: 0 }, 800);
            return false;
        });

An example of what I'm trying to do is for a main navigation link to a Contact div to scroll down to the href="#contact".

I've tried setting up if/else statements but to no avail, it could be down to a rough New Years night.

EDIT the hrefs I'm using are unique ids for each div that I want to scroll to.

Upvotes: 0

Views: 222

Answers (1)

jmore009
jmore009

Reputation: 12923

you can do

$('html, body').animate({scrollTop:$('#section-name').offset().top});

EDIT

I'll further explain the #section-name part: it's whatever you want, id, class you can use $("a"), $("div"), it's a selector.

So you can add a class to your href and target that class name if you want.

UPDATE

If you want to find the value of the href you choose you can do (I'm assuming .scrollToTop is a class name on an a tag?):

$('.scrollToTop').click(function () {
    var locationName = $(this).attr("href");
    $('html, body').animate({scrollTop:$(locationName).offset().top});
}):

Upvotes: 2

Related Questions