Hello DP members i have a jquery problem. whenever i tried to apply on click scroll script i got this error "uncaught typeError: cannot read property 'top' of null". Here following is code of Jquery.How can this will be fixed. $(document).ready(function($){ $('a[href^="#"]').bind('click.smoothscroll',function (e) { e.preventDefault(); var target = this.hash, $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top }, 900, 'swing', function () { window.location.hash = target; }); }); });
$target.offset() is null, so it has no top property (or any property at all). Debug back from there and see where the null is coming from.
#top is null and will return NaN so rather than waste time on this I would just altered the code to be: $(document).ready(function($){ $('a[href^="#"]').bind('click.smoothscroll',function (e) { e.preventDefault(); var target = this.hash, var topOffset = 0; //#top should default to 0 so no need to calculate the difference between top and top if (target != "#top") { //If the var topOffset = $(target).offset().top; } $('html, body').stop().animate({ 'scrollTop': topOffset }, 900, 'swing', function () { window.location.hash = target; }); }); });
If you are going to use this code, you should check the link URL to be sure that you want to preventDefault. If the #targetA does not exist on your current page, the above code would just make the link not work because $(target).offset().top will throw an error. What I mean is if the link goes to another page, then you do not want to interfere with the default behavior. Here is how I suggest doing it: $(document).ready(function($){ $("a").on('click', function (e) { //Only do the smooth scrolling If the link has a hash and the link is pointing to this same page. if (this.hash !== "" && this.pathname == window.location.pathname) { e.preventDefault(); var target = this.hash; var topOffset = 0; //#top should default to 0 so no need to calculate the difference between top and top if (target != "#top") { //If the target is not "#top", then calculate topOffset var topOffset = $(target).offset().top; } $('html, body').stop().animate({ 'scrollTop': topOffset }, 900, 'swing', function () { window.location.hash = target; }); } }); });