Using JavaScript to Scroll to a specific element/object.


This morning I continued working on my Greasemonkey script for our ticket system.  I decided I wanted a ticket to scroll to the relevant information on load. As this location varies depending on the ticket, it would be necccessary to pick a specific page element and scroll to it. This turned out being slightly more complicated than I originally thought.

I searched Google for “get object position+javascript“. Using the helpful information on this page, I did the following:

//Finds y value of given object
function findPos(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		do {
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	return [curtop];
	}
}
//Get object
var SupportDiv = document.getElementById('customer_info');
 
//Scroll to location of SupportDiv on load
window.scroll(0,findPos(SupportDiv));

It’s pretty easy and works just like I wanted it to.

,

  1. #1 by Joseph Ghassan at March 1st, 2009

    Was looking for that!

    Thanks Clifton!

  2. #2 by Paul B. at May 22nd, 2009

    I was just about to pop an artery trying to position the screen. Thanks to your suggestion, I survive until the next challenge!

(will not be published)