Dheeraj Chahar Dheeraj Chahar - 5 months ago 17
jQuery Question

Insert jQuery and JavaScript into HTML programatically in iOS

Have seen this code but I am not able to run it properly.

- (void)viewDidLoad {
[super viewDidLoad];
_webview.delegate = self;
[_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"Samplehtml" ofType:@"html"]isDirectory:NO]]];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *jsFile = @"jquery-1.11.0";
NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:jsFile ofType:@"js"];
NSURL *jsURL = [NSURL fileURLWithPath:jsFilePath];
NSString *javascriptCode = [NSString stringWithContentsOfFile:jsURL.path encoding:NSUTF8StringEncoding error:nil];
[_webview stringByEvaluatingJavaScriptFromString:javascriptCode];
}


So this is what i am trying.

MyJavaScript.js

$("p").click(function() {
alert("hello");


})

Samplehtml.html

<!DOCTYPE html>





<h1>My First Heading</h1>

<p>My first paragraph.</p>

</body>



Answer

Change your code like this. It is working on my side

-(void)viewDidLoad {
    [super viewDidLoad];
    self.webView.delegate = self;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Samplehtml" ofType:@"html"];
    NSString *htmlContent = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    [self.webView loadHTMLString:htmlContent baseURL:[NSURL URLWithString:@""]];
}

After that inside your webViewDidFinishLoad

- (void)webViewDidFinishLoad:(UIWebView *)webView {
     NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:@"simple" ofType:@"js"];
     NSURL *jsURL = [NSURL fileURLWithPath:jsFilePath];
     NSString *javascriptCode1 = [NSString stringWithContentsOfFile:jsFilePath encoding:NSUTF8StringEncoding error:nil];
     jsFilePath = [[NSBundle mainBundle] pathForResource:@"simple2" ofType:@"js"];
     jsURL = [NSURL fileURLWithPath:jsFilePath];
     NSString *javascriptCode2 = [NSString stringWithContentsOfFile:jsFilePath encoding:NSUTF8StringEncoding error:nil];
     [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"%@\n%@",javascriptCode1, javascriptCode2]];
}

Hope this will help you.