batgerel.e
batgerel.e

Reputation: 857

Scrolling anchor to sections

I have a problem with scrolling anchor elements to the sections. When i click the link it must be scroll to top of section. But my example going to middle of section.

<div class="anchor-container">
  <a href="#section1">Section 1</a>
  <a href="#section2">Section 2</a>
  <a href="#section3">Section 3</a>
  <a href="#section4">Section 4</a>
  <a href="#section5">Section 5</a>
</div>

What did i do wrong ? Any advice ? Here is a example

Upvotes: 1

Views: 425

Answers (2)

Kamalesh M. Talaviya
Kamalesh M. Talaviya

Reputation: 1420

you need to leave some space at top equal to anchor-container's height here i take innerHeight of anchor-container to take space including padding, see here

 $(document).on('click', 'a[href^="#"]', function (event) {
        event.preventDefault();
            var topmenu = $(this).parent('.anchor-container').innerHeight()
        $('html, body').animate({
            scrollTop: $($.attr(this, 'href')).offset().top - topmenu
        }, 500);
    });

Upvotes: 2

sol
sol

Reputation: 22949

You need to consider the height of your fixed Header.

...
 var headerHeight = $('.anchor-container').height();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top - headerHeight
    }, 500);
...

Updated codepen

Upvotes: 0

Related Questions