user1752759
user1752759

Reputation: 635

.js ScrollTop to div or section tag

I have the following script that allows me to add an anchor-link with a .class attached to my HTML document, which would then scroll the user to a position on the webpage when clicked on.

HTML:

<li class="about-scroll">About</li>

JavaScript:

$('.about-scroll').click(function () {
    $('body,html').animate({
        scrollTop: 646
    }, 1600);

    return false;
});

This works fine, however, as the content isn't always static (drop-down accordions, a responsive layout etc.), how would I be able to scroll to a specific #div or section tag rather than a numeric value on the page?

Example:

<div class="about">
    <h3>About</h3>
    ...
    ...
    ...
</div> <!-- end .about -->

Upvotes: 1

Views: 1456

Answers (2)

borbulon
borbulon

Reputation: 1411

If you're OK with no animation you can go with the answer which says just give the element you want to go to an ID and reference it with href="#the_id_you_placed"

for animation, you can still use the ID, but find the offset and animate to there:

$('.about-scroll').click(function () {
    $('body,html').animate({
        scrollTop: $('#the_id_you_placed').offset().top
    }, 1600);

    return false;
});

Upvotes: 1

Cody Guldner
Cody Guldner

Reputation: 2896

Give the h3 an id, say header. Then, you would reference the click event by using href="#header"

HTML

<h3 id="hi">HIIIIII</h3>
<a href="#hi">Scroll to Top</a>

jQuery

$('a').on('click', function (e) {
  e.preventDefault();                 // prevents default action of <a>
  var target = this.hash,             // gets the href of the <a>
      $target = $(target);            // puts it as a selector
  $('html, body').stop().animate({
    'scrollTop': $target.offset().top // scrolls to the top of the element clicked on
    }, 900, 'swing', function () {
    window.location.hash = target;
  });
});

Fiddle

The great thing about this function is that it is reuseable

Upvotes: 3

Related Questions