1

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

batgerel.e
  • 837
  • 1
  • 10
  • 31

2 Answers2

2

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);
    });
Kamalesh M. Talaviya
  • 1,422
  • 1
  • 12
  • 26
0

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

sol
  • 22,311
  • 6
  • 42
  • 59