Scrolling to some A NAME position in the page

16 views
Skip to first unread message

Varun Soundararajan

unread,
Oct 26, 2006, 10:58:56 AM10/26/06
to Google Web Toolkit
Hi,
I have a several <A Name="x"> areas in the page. When the user does
some UI Operations, such as clicking a button, how do I scroll down to
that <A NAME> in the page.
In Javascript, I understand that we set window.location="#x", but how
do we accomplish this with GWT. I saw Window class, but didnt have
location. Am I missing something?

Regards
Varun

Eric B

unread,
Oct 26, 2006, 1:21:31 PM10/26/06
to Google Web Toolkit
You could write your own JSNI function like this:

public static native void gotoAnchor( String name ) /*-{
$wnd.location = "#" + name;
}-*/;

However, some browsers refresh when you do this, which means that your
GWT code would be reloaded every time. This would be prohibitively
expensive for my apps (which tend to be large), so here's another way:

// This is javascript, you'll have to convert to JSNI
function scrollToElement(elementID)
{
var theElement = $(elementID);
if(theElement != null)
{
var selectedPosX = 0;
var selectedPosY = 0;

while(theElement != null){
selectedPosX += theElement.offsetLeft;
selectedPosY += theElement.offsetTop;
theElement = theElement.offsetParent;
}

window.scrollTo(selectedPosX,selectedPosY);
}
}

Hope this helps,
Eric

Varun Soundararajan

unread,
Oct 27, 2006, 8:07:11 AM10/27/06
to Google Web Toolkit
Thanks a lot Eric, the code worked.

As a help to future readers, I m converting it to JSNI and pasting it
here
put this code inside your native JSNI function

public static native void gotoAnchor( String elementID) /*-{
var theElement = $doc.getElementById(elementID);


if(theElement != null)
{
var selectedPosX = 0;
var selectedPosY = 0;

while(theElement != null){
selectedPosX += theElement.offsetLeft;
selectedPosY += theElement.offsetTop;
theElement = theElement.offsetParent;
}

$wnd.scrollTo(selectedPosX,selectedPosY);
}

}-*/;

Reply all
Reply to author
Forward
0 new messages