coder
coder

Reputation: 5390

How to trigger href link programmatically using Objective C

What I need to do is when I click a button or do a certain action, I want to have the webview transferred as if I have clicked on an href link the function should take the href id to know which link to go to.

Here's what I have tried so far:

      [WebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.location.hash='%@'",footNoteNum]];
    float offsetX = [[WebView stringByEvaluatingJavaScriptFromString:@"window.pageXOffset"] floatValue];
    NSLog(@"offsetX %f", offsetX);
    int page = ceil(offsetX/748);

    page++;
    NSLog(@"page %i", page);
    [self scrollToPage:page];

But when webview is greater then 25 pages it starts giving wrong numbers for offsetX.

So I thought if I can do just like an href link that can be clicked dynamically so when I use the scrollbar it would take me to the right position in the webview.

Upvotes: 0

Views: 775

Answers (2)

Mazen K
Mazen K

Reputation: 3662

- (void)viewDidLoad
{
   [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"YOUR_STRING_WITHOUT_ANCHOR"]]];
}

- (void)webViewDidStartLoad:(UIWebView *)_webView {
   [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('YOUR_ANCHOR_HERE_WITHOUT_#').scrollIntoView(true);"];
}

Upvotes: 0

john.k.doe
john.k.doe

Reputation: 7563

the way i have accomplished a similar problem (click on a particular tableView row and have it go to a specific location in a UIWebView in the same scene) is to embed anchors in the html, and then navigate straight to them. this assumes, of course, you have control over navigating to your footnotes in such a manner.

the anchors just sit at each page in your html right before the text of each of your footnotes like this:

<a name=footnote12>

and then in your code, you would have:

    // baseURLForPageWithoutAnchor is the NSURL* for the page prior to going to any footnotes

    NSString* anchor = [@"#" stringByAppendingFormat:@"footnote%d", footNoteNum];
    NSString* baseForAnchor = baseURLForPageWithoutAnchor.absoluteString;
    NSURL* anchorURL = [NSURL URLWithString:[baseForAnchor stringByAppendingString:anchor]];
    [self.nestedWebView loadRequest:[NSURLRequest requestWithURL:anchorURL]];

this will jump straight to the anchor, and the need for calculating the percentage into the UIWebView that you have been trying to scroll by percentage is eliminated.

Upvotes: 1

Related Questions