4thSpace
4thSpace

Reputation: 44352

How to reference an HTML anchor

I'm loading a string of HTML into a UIWebView through loadHTMLString. It produces a very long webpage. Once that string is loaded, I need to navigate to an HTML anchor tag with its "name" attribute set. In the HTML, I might have:

//3 pages of text here
<a name="go here"></a> lots more text here
//another 3 pages of text here

I need the webpage to scroll down to "go here" once loaded. The mappings work fine if a user clicks a link inside of the webpage and it loads an external URL. But in this case, I need to initially scroll down an already loaded webpage.

I can still execute JavaScript code like this:

[MyWebView loadHTMLString:dataString baseURL:[NSURL URLWithString:@"http://www.myscheme.com"]];
[webView stringByEvaluatingJavaScriptFromString:@"javascriptFunc('param1');"];

But I need something similar for navigating to the anchor tag. Any suggestions?

Upvotes: 4

Views: 3580

Answers (2)

Neil N
Neil N

Reputation: 25268

If I'm not mistaken, just add #go%20here to the end of the URL.

Ahh, you mean already loaded. Is it really out of the question to just do reload the page? The browser should have cached most of it anyway...

Upvotes: 1

edward de jong
edward de jong

Reputation: 124

You can jump to an anchor in an already-loaded HTML file by doing:

[webView stringByEvaluatingJavaScriptFromString:@"window.location.hash='#foo'"];

This will do the jump, sans animation.

Upvotes: 10

Related Questions