0

I get the following error:

Uncaught TypeError: Cannot read property 'top' of undefined

$(document).ready(function() {
  $(function() {
    $('a[href*="#"]').on('click', function(e) {
      e.preventDefault();
      $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top
      }, 500, 'linear');
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrollDown">
  <a href="#nextSection"><span></span>toliau</a>
</div>

1
  • You get that error because the #nextSection element doesn't exist, hence offset() is undefined, and trying to access a property of an undefined object gets you the error you're seeing. Commented Sep 11, 2017 at 10:18

2 Answers 2

1

Just change this line i hope it will work

 scrollTop: $($(this).attr('href')).offset().top

To this

  scrollTop: $(this).offset().top
Sign up to request clarification or add additional context in comments.

Comments

1

$(document).ready(function() {
  $(function() {
    $('a[href*="#"]').on('click', function(e) {
      e.preventDefault();
      $('html, body').animate({
          scrollTop: $(this).offset().top
      }, 500, 'linear');
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrollDown">
  <a href="#nextSection"><span></span>toliau</a>
</div>

2 Comments

Copied my answer what is the change
The difference between our answers is you have given change while i have given working output and if you believe that answer#copied than you can check my past answers i have given many answers on offset. BTW thank you for your down vote :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.