Matt Lee
Matt Lee

Reputation: 571

Jquery - Uncaught TypeError: Cannot read property 'top' of undefined

I've seen lots of entries with this title but none that helped my specific problem. I don't know what the problem could be. I followed a youtube tutorial and did exactly what they did. But when I click on my anchor link, nothing happens and I get this error in the console: Uncaught TypeError: Cannot read property 'top' of undefined.

This is my Javascript:

<script>
    $(function() {
        $("a").click(function() {
            if(this.hash) {
                var hash = this.hash.substr(1);

                var $toElement = $("a[name="+hash+"]");
                var toPosition = $toElement.position().top;

                $("body,html").animate({
                    scrollTop : toPosition
                },2000,"easeOutExpo");
                return false;
            } 
        });
    });
</script>

Jsfiddle with my full code

Upvotes: 0

Views: 1804

Answers (3)

Matt Lee
Matt Lee

Reputation: 571

Your answers helped me come to a solution. I was trying to make it scroll to a div. Not an href or an a tag. I finally got it in order and it scrolls to the right places and it works for all the buttons on my site now. Thanks, all who helped me come to this.

Upvotes: 1

Sabith
Sabith

Reputation: 1656

Top of undefined error occurs because of accessing 'top' style of an element that is not defined. here change

var $toElement = $("a[name="+hash+"]");

To

var $toElement = $("a[href=#"+hash+"]");

Hope it will solve your problem

Upvotes: 2

Jai
Jai

Reputation: 74738

The issue is your target element doesnot have a name attribute:

<a href="#about_me" id="scroll_down">About Me</a>

As you can see above there is no name attribute, Either you add it

<a href="#about_me" name="about_me" id="scroll_down">About Me</a>
<!------------------^^^^^^^^^^^^^^-----add this----->

or change the href to name and remove the #:

<a name="about_me" id="scroll_down">About Me</a>
<!-^^^^^^^^^^^^^^-----change href to name----->

Updated Fiddle with easings.

In the fiddle you have to use easing code as the easing you are using is not available in the jQuery, so you have to put the code/library.

Upvotes: 3

Related Questions