Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'top' of undefined

Tags:

jquery

scroll

Trying to get the page to scroll to an anchor and I'm getting this error.

Cannot read property 'top' of undefined

Right now I have my JS like the following...

//scroll to section process page
function scrollToAnchor(aid){
    var aTag = $("div[name='"+ aid +"']");
    $('html,body').animate({scrollTop: aTag.offset().top},'slow');
}

$("li.menu-item-141 a").click(function() {
   scrollToAnchor('#philosophy-page');
});

Here is my HTML...

<div class="container">
<div name="philosophy-page" id="philosophy-page">
    <div class="philosophy-heading">
        <h1>Philosophy</h1>
    </div><!-- /.philosophy-heading -->
</div><!-- /#philosophy-page -->
</div><!-- /.container -->

Any help would be great!

Thank you!

like image 378
bryanlewis Avatar asked Apr 09 '13 16:04

bryanlewis


2 Answers

replace

scrollToAnchor('#philosophy-page');

by

scrollToAnchor('philosophy-page');

Remember you use the name to find the a element:

var aTag = $("div[name='"+ aid +"']");

jQuery cannot find an element named #philosophy-page

like image 162
Adriano Carneiro Avatar answered Nov 06 '22 10:11

Adriano Carneiro


$(function() {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

Best scroll to I have found. Found it on CSS Tricks: https://css-tricks.com/snippets/jquery/smooth-scrolling/

like image 5
Carl Sergile Avatar answered Nov 06 '22 11:11

Carl Sergile