Reputation: 15
I am using scrollTo function in jQuery to do smooth scrolling to an element on the page. While I click a link with target inside the same page it works fine.
My problem is I also want this to work on external pages directly on page load (otherDoc.aspx?a=elementId and the if Request.QueryString...). The problem is that it doesn't scroll to quite the right position which I think is because all content may not be fully loaded so the elements position changes, which means the result would be even worse on a slow connection. I tried to do a setTimeout to test with delay and then it scrolls to the right position. An option is to do simple anchors #myAnchor on the external links, but the smooth scroll gives a nicer feeling.
My code:
<script>
$(document).ready(function () {
$(window).scrollTo("#" + elementId, 1000);
});
</script>
Any suggestions? Thanks!
Upvotes: 0
Views: 2331
Reputation: 106
$(document).ready() fires when the html and head scripts are loaded... you should try $(window).load() instead as that fires when the whole page including all assets are loaded-- I hear though that some cached images might not count so test it out with a hard refresh but you'll likely achieve your desired effect.
I don't know your URL but sometimes the position of your anchor element you are targeting might have styles affecting its height or if it's rendered as a block element and sometimes that could play into where you scroll to. If you can I would add a top-padding to your anchor elements especially if they start a SECTION or ARTICLE so that you can have a little space on top so the heading text isn't right at position 0 of the scroll position, too.
Upvotes: 7