brent_white
brent_white

Reputation: 1019

jQuery smooth scroll issue

I've followed this tutorial on how to write a little bit of jQuery to get a nice smooth scroll on my site. Here's the tut for you're reference https://www.youtube.com/watch?v=S6pzabpUmoc

However there seems to be an issue somewhere in my jQ code and the Animation is not working...It would be nice to have a fresh set of eyes on it to see where I am going wrong and how to fix it.

As of this moment the console is telling me that I have this issue TypeError: Cannot read property 'top' of undefined

Here is my current build http://kapena.github.io/pp_web/#services-pp

Here is my is jQ code

$(function() {
     // catch all clicks on page
     $('a').click(function() {

     // check if has hash
     if(this.hash) {

     // get rid of the # sign
     var hash = this.hash.substr(1);

     //get the position of the <a name>
     var $toElement = $("a[name="+hash+"]");
     var toPosition = $toElement.position().top;

     // scroll / animate that element
     $ ('body,html').animate({
        scrollTop : toPosition
     },2000,"easeOutExpo");

     // don't do the jump
     return false;

    }

     });

    if(location.hash) {
        var hash = location.hash
        window.scroll(0,0);
        $('a[href='+hash+"]").click();
    }        

});

Upvotes: 0

Views: 711

Answers (2)

Kholin
Kholin

Reputation: 3

Because $("a[name="+hash+"]") return nothing. Maybe you should check if it return something before the animation start. Just like this:

if($toElement.length){

    // do something

}

Upvotes: 0

Gayan C Liyanage
Gayan C Liyanage

Reputation: 354

below 'hash' is the place definitely you are having a erorr, Uncaught TypeError: Cannot read property 'left' of undefined occurs due to undefined element property accesssing.

$toElement = = $("a[name="+hash+"]"); // this hash is undifined or wrong value

// this lead following line to throw the error 
var toPosition = $toElement.position().top;

Upvotes: 1

Related Questions