简体   繁体   中英

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 or on-load. It's just called on specific click-events.

thank you for your help

您确定在页面上定义了#selector吗?

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.

PS: PhpStorm has the best debugger for JavaScript a ever seen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM