Reputation: 5271
Could not find a correct answer.
I'd like to open the page then animate scrolled to the ID
I called.
here is my code.
JQuery
$(window).bind("load", function () {
var urlHash = window.location.href.split("#")[1];
$('html,body').animate({ scrollTop: $('a[href="#' + urlHash + '"]').offset().top}, 1000);
});
Html
<div class="space"></div>
<div id="anchor">This is anchor</div>
css
.space{height:800px;}
#anchor{font-size:25px;height:800px;}
then jQuery is not working, so I pasted the following code to console
$('html,body').animate({ scrollTop: $('a[href="#' + anchor+ '"]').offset().top}, 1000);
The error says
TypeError: Cannot read property 'top' of undefined
How could I solve this error? thanks
Upvotes: 0
Views: 2260
Reputation: 14049
This code works: http://jsfiddle.net/4mjmw/4/
Demo: http://jsfiddle.net/4mjmw/4/show/#abc
I added an href to the anchor and moved the script to HTML.
$(window).bind("load", function () {
var urlHash = window.location.href.split("#")[1];
$('html,body').animate({ scrollTop: $('a[href="#' + urlHash + '"]').offset().top}, 1000);
});
Upvotes: 3