简体   繁体   中英

Uncaught TypeError: Cannot read property 'top' of undefined - Scrolling error?

Here is my HTML:

<ul class="nav-list">
   <li class="current"><a class="smoothscroll" href="#home" title="">Home</a></li>
    <li><a class="smoothscroll" href="signup.html" title="">Sign up</a></li>
    <li><a class="smoothscroll" href="signin.html" title="">Sign in</a></li>                
</ul>

Here is my JavaScript:

var ssSmoothScroll = function() {
    $('.smoothscroll').on('click', function (e) {
        var target = this.hash,
        $target    = $(target);

        e.preventDefault();
        e.stopPropagation();        

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, cfg.scrollDuration, 'swing').promise().done(function () {
           // check if menu is open
           if ($('body').hasClass('menu-is-open')) {
               $('#header-menu-trigger').trigger('click');
           }

           window.location.hash = target;
        });
    });
};

I trawled through several answers to this and still cannot find why mine isn't working. Any help is much appreciated.

I want to continue on to either signup.html or signin.html but neither of the links work if I click them. They only work if I right click and open in new tab.

The only reason offset will return undefined is if you call it on an empty jQuery set. So that tells us that $(target) is returning an empty jQuery set, presumably because target contains a selector that doesn't match any elements.

You probably want to add a guard to allow for that:

if (!$target.length) {
    return;
}

...just after $target = ... .


Looking at your HTML, though: You probably just want to remove the smoothscroll class from the links that take you to another page (the second two in your example). The only purpose they seem to have is to make jumping to anchors within the page scroll rather than jump. Since those links are off-page, I'd just not put the class on them in the first place.

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