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
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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.