• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2213
  • Last Modified:

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>

Open in new window

0
hankknight
Asked:
hankknight
  • 2
2 Solutions
 
viral_sonawalaCommented:
Include script tags pointing to the external JavaScript files.

Place nested div's  in the document where you wish the scroll area(s) to appear.

Adjust style specifications for the div's.

Add scroll controls and/or scrollbar elements.

Initialize the code.

0
 
sunithnairCommented:
0
 
-null-Commented:
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-

0
 
-null-Commented:
p.s.

This is the kind of code you need.  You can pass the result of this to scrollTo, eg.

window.scrollTo(0, absTop("spot"));



Alternatively, you could use anchoring;

http://www.webdesign.org/web/html-and-css/tutorials/using-name-tag.11137.html

Similar in functionality, but negates the need for javascript.

-null-
function absTop(elementId){	
        var obj = document.getElementById(elementId);
	var offset = 0;
	while(obj.offsetParent) {
		offset += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return(offset);
}

Open in new window

0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now