1

I've been trying to implement a smooth scroll to top using the this CSS-Tricks Snippet.

Now I have the following HTML:

<!-- At the top of the page -->
<p id="content_jump" class="hide">
    <a id="#top"></a>
</p>

<!-- A bunch of content -->

<!-- At the bottom of the page -->
<a rel="nofollow" href="#top" id="backtotop" title="Go to top" onclick="scrollToTop();">
    Back to Top
</a>

Then I have the following script:

function scrollToTop() {
    $('html, body').animate({
        scrollTop: $("#top").offset().top
    }, 1000};
    return false;
}

I expect this to smoothly scroll to the top of the page over the period of 1 second.

However, when I click "Back to Top" it instantly goes to the top and the console provides me with the following error:

Uncaught TypeError: Cannot read property 'top' of undefined
    at scrollToTop ((index):274)
    at HTMLAnchorElement.onclick (VM1390 :245)

Any idea on a solution to the problem would be much appreciated.

3
  • 2
    you have id as #top , thats why your selector does not match Commented Jan 23, 2017 at 14:48
  • You have no element with the id of top. If you want to go to the top of the page just use scrollTop: 0 Commented Jan 23, 2017 at 14:48
  • Thanks guys, spotted it. Typical Mondays :P Commented Jan 23, 2017 at 15:00

1 Answer 1

3

It's throwing that error because it can't find your element with an id of top.

Looking at your code, you have an error in your id name.

<a id="#top"></a> 

should be

<a id="top"></a>
Sign up to request clarification or add additional context in comments.

2 Comments

Ah what a rookie error, thanks for spotting that! I'll accept soon :)
@BarryMichaelDoyle happens to the best of us!

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.