2

As per this question, I've used the following code:

$("a.smooth-scroll").click(function(e) {
        e.preventDefault();
        $('html, body').animate({
            scrollTop: $( $.attr(this, 'href') ).offset().top
        }, 1000);
    });

My HTML looks like this:

<a href="#product-list" class="btn btn-default smooth-scroll"><span class="fa fa-list-ul"></span>Full Product List</a>

And the corresponding link:

<a name="product-list"></a>

Yet I get a javascript error: shop.js:8 Uncaught TypeError: Cannot read property 'top' of undefined

Why is this?

Community
  • 1
  • 1
Chud37
  • 4,907
  • 13
  • 64
  • 116

2 Answers2

0

$.attr(this, 'href') (alternatively, $(this).attr('href')) for your link will return the string #product-list.

When running $('#product-list') it looks for elements with an id of product-list, which in this case returns no elements. Trying to get the offset() of an empty set returns undefined. You can not access properties of undefined, that is why your code isn't working.

Alternatively, I'd consider using a solution like the one found here - https://css-tricks.com/snippets/jquery/smooth-scrolling/

romellem
  • 5,792
  • 1
  • 32
  • 64
  • Then why is it the top answer in the linked question? And how come their JSFiddle works? (http://jsfiddle.net/9SDLw/) – Chud37 Mar 24 '16 at 10:30
  • If you read the second part of [their answer](http://stackoverflow.com/a/7717572/864233), "*If your target element does not have an ID, and you're linking to it by its `name`, use this:*" then some different code is listed which strips out the hash sign (`#`). – romellem Mar 24 '16 at 13:25
0

It's not a solution of your existing code. But maybe you can use my working script:

 $(".scroll").click(function(event){
         event.preventDefault();
         //calculate destination place
         var dest=0;
         if($(this.hash).offset().top > $(document).height()-$(window).height()){
              dest=$(document).height()-$(window).height();
         }else{
              dest=$(this.hash).offset().top;
         }
         //go to destination
         $('html,body').animate({scrollTop:dest}, 1000,'swing');
     });

You have to add class="scroll" at the <a href="#product-list">. Check the Fiddle: http://jsfiddle.net/YtJcL/1409/

Cornest
  • 269
  • 1
  • 15