jquery / javascript: Uncaught TypeError?
hey guys, i wrote a little custom animated scroll function...
function scroll(selector, animate, viewOffset) {
pageOffset = selector.offset();
scrollPos = pageOffset.top - viewOffset;
if (animate) {
$('html, body').animate({scrollTop : scrollPos + 'px'}, {
duration: 'slow', // how fast we are animating
easing: 'easeOutQuint', // the type of easing
complete: function() { }
});
} else {
$('html, body').scrollTop( scrollPos );
}
}
I call it with scroll($('#something'), false, 30);
It actually works, however sometimes it's a little bit buggy and the function doesn't properly work. I always call the scroll() function on a click-event.
The biggest problem I have is that on page load my console tells me the following line.
Uncaught TypeError: Cannot read property 'top' of null (script.js line 191 which is line 3 in my example above)
Any idea what could cause this error? the scroll() function is not even called on dom-ready o开发者_运维百科r on-load. It's just called on specific click-events.
thank you for your help
Shouldn't it be:
pageOffset = $(selector).offset();
?
I usually get same "mysterious errors" with selector mistypes.
Wrap all code in your function with try/catch statement and try to debug it. There are debug tools in almost all major browsers. Set a breakpoint inside catch statement and then your script hit there look at pageOffset and selector variables.
P.S.: PhpStorm has the best debugger for JavaScript a ever seen.
Are you sure you have #selector defined on your page?
精彩评论