Reputation: 569
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!
Upvotes: 12
Views: 54905
Reputation: 51
$(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/
Upvotes: 5
Reputation: 58615
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
Upvotes: 14
Reputation: 148120
Pass id without #
as name does not #
in it.
Change
scrollToAnchor('#philosophy-page');
To
scrollToAnchor('philosophy-page');
Upvotes: 1