partlycloudy
partlycloudy

Reputation: 429

Using jQuery with google.load

I am trying to understand how to use jQuery when it is loaded using Google CDN's google.load method.

Putting the init code in the setOnLoadCallback function works great but defining functions for event handlers in the markup doesn't seem to work. In the example below, the P button works as expected but the Div button does nothing.

Yes, in this example, I can put the div's onclick handler also in the setOnLoadCallback function but does that mean that all jQuery code has to be there?

Help? Thanks

<p id="p">Content</p><button type="button" id="btn1">P</button>

<div id="div">Div</div><button type="button" id="btn2" onclick="btn2()">Div</button>

<script src="http://www.google.com/jsapi"></script>

<script>

function btn2() {
 $("#div").toggle("slow");
}

google.load("jquery", "1.3.2");
google.setOnLoadCallback(function() {
$("#btn1").click(function () {
      $("p").toggle("slow");
});
});

</script>

Upvotes: 1

Views: 1549

Answers (3)

Chris Clark
Chris Clark

Reputation: 4794

Yes, you need to have all your jQuery code inside setOnLoadCallback if you want to load jQuery this way. Until that event fires, there is no guarantee that the jQuery script has loaded, and thus any jQuery code outside that function may be invalid. If you want to define jQuery code outside of that event, you can do it by loading jQuery from Google's CDN URL instead of dynamically by google.load().

The url for jQuery from Google's CDN looks like this:

http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

You can just include it in the head of the document as an external script resource as usual. You still get the benefits of the Google CDN because most browsers will have a cached copy of jQuery at that location (assuming they have visited another site that used the Google CDN).

Upvotes: 0

carillonator
carillonator

Reputation: 4743

Put your Google jsapi script call and google.load at the top of <head> in your document. When run, it will just output

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" 
    type="text/javascript"></script> 

where google.load was.

Then put all your jQuery code inside:

$(function() {
    // all your jQuery code here
});

which is shorthand for $(document).ready(function(){ });

Upvotes: 2

prodigitalson
prodigitalson

Reputation: 60413

One of the key points of JQ is to be unobtrusive thus you shouldnt be using <element onclick="..."></element>. You should always be using $(selector).click(). Furthermore you generally want to have this consolidated in a single $(document).ready();, or in exeternal scripts.

Upvotes: 0

Related Questions