hankknight
asked on
Scroll to div by id with JavaScript
Using only JavaScript, how can I scroll so that the div with an id of "spot" is in the top left part of the window?
<div id="spot"></div>
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Please see it here http://www.howtocreate.co.uk/fixedPosition.html
Hi,
You need to know how far down the page that tag is in pixels so that you could use something like scrollTo. To achieve this, you can use the offsetTop property of the div. However, this returns the number of pixels the div is from the top of it's parent container.
What you need to do therefore is measure the offsetTop of the spot div, then test it's parent property. If the div has a parent, you need to measure the parent's offsetTop, then test if that has a parent. This continues until you reach the html tag, which doesn't have a parent. At this point, having added up all the offset tops in your loop, you have an accurate measure of exactly how far down the page the tag is. You can then pass this value to scrollTo.
hth
-null-
You need to know how far down the page that tag is in pixels so that you could use something like scrollTo. To achieve this, you can use the offsetTop property of the div. However, this returns the number of pixels the div is from the top of it's parent container.
What you need to do therefore is measure the offsetTop of the spot div, then test it's parent property. If the div has a parent, you need to measure the parent's offsetTop, then test if that has a parent. This continues until you reach the html tag, which doesn't have a parent. At this point, having added up all the offset tops in your loop, you have an accurate measure of exactly how far down the page the tag is. You can then pass this value to scrollTo.
hth
-null-
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.