0

I want to use smooth scroll to go to the anchors on my homepage. I use this jQuery code:

$(document).ready(function(){
    $('a').click(function(){
        $('html, body').animate({
            scrollTop: $($.attr(this, 'href')).offset().top
        }, 1000);
            return false;
    });
});

And this is the HTML code:

<div id="menu">
        <div id="menu-contain">
            <ul>
                <li><a class="home" href="#">Home</a></li>
                <li><a class="about" href="#about">About</a></li>
                <li><a class="projects" href="#projects">Projects</a></li>
                <li><a class="contact" href="#contact">Contact</a></li>
            </ul>
        </div>
    </div>

This works quite fine for every anchor but the first. If I have a look at the console there is an error if I click on the first link:

Cannot read property 'top' of undefined

I found a lot of threads to this error but I didn't find a solution which works for me.

Suggestions appreciated :)

Tyler
  • 882
  • 4
  • 18
  • 32

1 Answers1

1

Check for the existence of your target element before using it:

$('a').click(function(){
    var $target = $($.attr(this, 'href'));

    if ( ! $target.length ) return;

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 1000);

    return false;
});

You should also cache your selector there. See this thread for more details.

Community
  • 1
  • 1
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • Thanks for the answer. The error in the console is away now but the smooth scroll does still not work for the first anchor. You know why? And thanks for the link to cache my selector. I will look at it. – Tyler Feb 23 '14 at 02:15