We help IT Professionals succeed at work.

Scroll to div by id with JavaScript

hankknight
hankknight asked
on
Medium Priority
2,386 Views
Last Modified: 2012-05-06
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

Comment
Watch Question

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.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

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-

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

Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.