Skip to content

Instantly share code, notes, and snippets.

@walm
Created September 16, 2011 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walm/1223291 to your computer and use it in GitHub Desktop.
Save walm/1223291 to your computer and use it in GitHub Desktop.
Forward scrollToTop event to webview in PhoneGap iOS
// add UIScrollViewDelegate
@interface AppDelegate : PhoneGapDelegate <UIScrollViewDelegate>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//.. phonegap's code //
BOOL result = [super application:application didFinishLaunchingWithOptions:launchOptions];
// disable scrolltotop in webview as we add our dummy scrollview to catch this event
// only one scrollview can catch the event
if ([[self.webView subviews] count] > 0) {
UIScrollView *scrollView = (UIScrollView *)[[self.webView subviews] objectAtIndex:0];
if ([scrollView respondsToSelector:@selector(setScrollsToTop:)]) {
[scrollView setScrollsToTop:NO];
}
}
// dummy scrollview to catch scrolltotop event
UIScrollView *dummyScrollView = [[UIScrollView alloc] init];
dummyScrollView.delegate = self;
[self.viewController.view addSubview:dummyScrollView];
[self.viewController.view sendSubviewToBack:dummyScrollView];
dummyScrollView.contentSize = CGSizeMake(self.viewController.view.frame.size.width,
self.viewController.view.frame.size.height+200);
dummyScrollView.contentOffset = CGPointMake(0, 1);
[dummyScrollView release];
return result;
}
// forward event to webview as scrollToTop event on document using jQuery/zepto.js
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView
{
NSLog(@"scrollViewShouldScrollToTop");
NSString *jsString = @"if (typeof $ === 'function' && typeof $(document).trigger === 'function') $(document).trigger('scrollToTop');";
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
return NO;
}
@walm
Copy link
Author

walm commented Sep 16, 2011

In your webpage then just listen to scrollToTop on document

$(document).bind('scrollToTop', function(){ /* your stuff.. */ });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment