tags:

views:

593

answers:

3

Why does the browser not scroll to the anchor?
url:http://localhost:8080/index.html#myAnchor3

this.anchor1.setName("myAnchor1");
this.add(this.anchor1);
this.anchor2.setName("myAnchor2");
this.add(this.anchor2);
this.anchor3.setName("myAnchor3");
this.add(this.anchor3);

Is it because the anchor is created after the page has finished loading, so the browser doesn't see the anchor when it tries to scroll to it?

+1  A: 

Try this:

this.anchor.setName("myAnchor");
this.add(this.anchor);
location.hash = '#myAnchor';

And yes, you are right, your anchor was created/inserted after the page load, so well.....

o.k.w
where is location.hash in scope? location is in scope, but it only has accessor methods, no direct access or setter methods.
antony.trupe
@antony: Are you saying it doesn;t work for you. It does for me. In full, it is "window.location.hash" (see https://developer.mozilla.org/en/DOM/window.location and http://msdn.microsoft.com/en-us/library/ms533775%28VS.85%29.aspx). It can be read/assigned.
o.k.w
ah, you jumped down to javascript.
antony.trupe
@anthony: ermm, everything you coded is javascript, ain't it? If you want the hash to be dynamic based on the one supplied in the URL, then set "location.hash = location.hash;" after you created the anchors.
o.k.w
my example code is all java
antony.trupe
@anthony: My apology, how could I miss that. If your anchor is defined before it is rendered to the browser, it should work.Did you check the HTML markup? You should see a '<a name="myAchor"....'
o.k.w
+1  A: 

You could try using Element.scrollIntoView(), which not only will scroll the window, but any scrollable container in the DOM hierarchy that holds the element.

spankalee
looks promising, I'll try it tonight.
antony.trupe
haven't gotten this to work yet, but not convinced I'm not doing something wrong yet.
antony.trupe
I was trying to scroll to an element that wasn't added to the DOM yet. Restructuring some code...
antony.trupe
A: 

Had to override the onLoad method, and call scrollIntoView there, otherwise it was trying to scroll to an object that wasn't added to the DOM yet.

public class Foo extends Widget
{
  Foo(){
  }

  @Override
  protected void onLoad(){
    super.onLoad();
    getElement().scrollIntoView();
  }
}
antony.trupe