views:

116

answers:

3

Hi,

I've added this code below to a MOSS 2007 web part inside OnPreRender() method.

if (!Page.ClientScript.IsClientScriptBlockRegistered("jump_to_anchor_JS"))
{
   Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "jump_to_anchor_JS", "window.location.hash=\"anchor\";",true);
}

The page loads, jumps to the specific anchor, then jumps back to the top of the page. This has been tested in IE8, Firefox, Chrome, and Safari with same behavior.

Any thought?

A: 

Try using:

ClientScript.RegisterStartupScript(...)

From the MSDN Article here:

The script block that is rendered by the RegisterStartupScript method executes when the page finishes loading but before the page's client onload event is raised. Startup script blocks are located at the bottom of the rendered ASP.NET page just before the form tag.

or use jQuery:

$(document).ready(function(){window.location.hash="anchor";});
Pete Amundson
I have tried both. With the first one, the page does not jump to the anchor at all. With the second one, same behavior. Thank you for helping though.
madatanic
Also, the default functionality of the www.example.com#my_anchor is to scroll down the page and find <a name='my_anchor'></a>
Pete Amundson
you can also add a timeout :) $(document).ready(function(){window.setTimeout('window.location.hash = "anchor";',1000);});
Pete Amundson
what does the timeout do. Sorry for my jquery noobness.
madatanic
it will fire the javascript to scroll to the anchor after 1 second (1000 milliseconds) - it is a cheat - but you can adjust it to whatever you want (2000 - 2s, 5000 - 5s) whatever works
Pete Amundson
setTimeOut did the trick, thank you!
madatanic
A: 

Are you including the "#" hash sign in front of your anchor name? i.e.,

window.location.hash = '#anchor';

Also, see window.location.hash issue in IE7 regarding using focus() or scrollIntoView() instead.

nekno
Tried this too, the # sign didn't make a difference.Also tried string.Format("document.getElementsByName('{0}')[0].scrollIntoView(true);", "anchor");. Didn't work either.Seems like SharePoint is messing with me.
madatanic
A: 

Try using

window.location.href = '#anchor';

Gary L Cox Jr