0

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?

madatanic
  • 1,760
  • 3
  • 16
  • 28
  • As mentioned, the page does not stay at the anchor that I want it to but jumps back to top of the page. – madatanic Aug 11 '10 at 20:27

3 Answers3

0

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
  • 890
  • 5
  • 16
  • 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 Aug 11 '10 at 20:26
  • Also, the default functionality of the www.example.com#my_anchor is to scroll down the page and find – Pete Amundson Aug 11 '10 at 20:31
  • you can also add a timeout :) $(document).ready(function(){window.setTimeout('window.location.hash = "anchor";',1000);}); – Pete Amundson Aug 11 '10 at 20:39
  • what does the timeout do. Sorry for my jquery noobness. – madatanic Aug 11 '10 at 20:44
  • 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 Aug 11 '10 at 21:17
0

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.

Community
  • 1
  • 1
nekno
  • 19,177
  • 5
  • 42
  • 47
  • 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 Aug 11 '10 at 20:43
0

Try using

window.location.href = '#anchor';

Gary L Cox Jr
  • 680
  • 3
  • 10