0

I have a div "content" with anchor id="one" inside of it.

Right now, I am using an onClick event from an exterior link to scroll "content" by a pixel distance to bring "one" into view without making the rest of the page jump and it works nice and smooth as planned...

onClick="document.getElementById('content').scrollTop = 400;

but I would rather calculate the exact offsetTop distance of "one" and scroll by that distance instead of my arbitrary numbers.

This is what I am trying:

<script type="text/javascript">
<!--
var topPos = document.getElementById('one').offsetTop;
//-->
</script>

and

onClick="document.getElementById('content').scrollTop = topPos;

with

<a id="one"></a> being how I ID the element within the content.

But topPos returns null! I can't seem to get past this. I don't know if it's my poor javascript skills (probably) or the fact that my css isn't providing any numbers. I am not using fixed positioning, if this matters. Can anyone tell me my glaring error? Thanks in advance.

3
  • check out quirksmode.org/js/findpos.html Commented Jun 15, 2011 at 20:38
  • If you're executing your script before <a id="one"> is created, that would explain it. Make sure you execute your script after that <a> is created. Commented Jun 15, 2011 at 20:39
  • Yes! Moving the JS to the bottom did indeed allow those variables to be calculated. Thanks so much for your help today. Commented Jun 15, 2011 at 20:51

2 Answers 2

1

Any reason not to use scrollIntoView()?

https://developer.mozilla.org/en/DOM/element.scrollIntoView

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, although it does scroll the div's content, scrollIntoView() also moves the parent page to center the "content" div in the browser window... the page jumps awkwardly, which is what I am successfully avoiding with this code.
It's an awesome answer.. It has met my requirement.. Thanks Chris
0

Depending on where the script is located, it may be because the browser does not yet have enough info to retrieve the topPos. Try placing the script at the bottom of the page or run it in response to a page load event. Alternatively, instead of calculating ahead, just have onClick call a function to calculate the position and set the scroll.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.