Attach script to jQuery ready method before jQuery is loaded - javascript

For example, bootstrap put the jQuery at the end of the html, e.g. http://twitter.github.com/bootstrap/examples/starter-template.html
What if, you want to insert a code block before the loading of jQuery script itself, e.g.
<div id="test1"></div>
<div id="test2"></div>
<script>
$(document).ready(function() {
$('#test1').html('test1'); // not work, any workaround? the code must be put before..
});
</script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
$('#test2').html('test2'); // work
});
</script>
Test: http://jsfiddle.net/e5HKZ/
I want both test1 & test2 also displayed.
Any idea?

If you really have to put jQuery code before the line that loads jQuery itself, assign the function to document.ready.
window.document.ready = function() {
$('#test1').html('test1');
};
When jQuery has been loaded, it reads the variable and executes the function at DOM ready.
Note that this is most likely undocumented behavior and might not work reliably or in future jQuery versions.
Demo: http://jsfiddle.net/e5HKZ/1/

Related

How to call jQuery function in HTML <body> onload?

I want to call a jQuery function from an HTML <body> tag. Here's my HTML:
< body bgcolor="#ffffff" onLoad="???" >
How would I call a jQuery function when the page is loaded? My jQuery function looks like this
jQuery(function($){
var input_id;
//code
});
whatever code you write in the below method(block) would be executed automatically after the DOM load. You need not call this from HTML component again.
$(document).ready(function() {
//your code
});
This topic has been covered here before.
You are most likely looking for
$(document).ready(function() {
var input_id;
//code
})
Or
$(window).load(function($) {
var input_id;
//code
});
If you are curious about the difference between these two, see the JQuery documentation on the topic.
Also note that <body onload="">, which you seem to be trying to use, is generally not compatible with the above JQuery.
$(function() {
// code
});
This is shorthand for document.ready() so it will wait for the body to finish loading before executing.
HTML: You're on the right track, but you do not have to have put JS in the body tag. See the JS options below:
<body bgcolor="#ffffff">
JS
$(window).load(function($) {
functionA(arg1, arg2, arg3);
});
This will fire up functionA() once the DOM including graphics have fully loaded.
OR
$(document).ready(function($) {
functionA(arg1, arg2, arg3);
});
This will fire functionA() once the DOM has loaded and before any graphics finish loading.
As of Jquery 3, the following syntax is depreciated:
document.ready(function(){
//code
});
The recommended alternative in Jquery 3 is to use the following syntax (which in previous versions was just considered a shorthand syntax):
$(function(){
//code
});
Here is is the official Jquery explanation for why the first syntax was depreciated and is no longer recommended (https://api.jquery.com/ready/):
... The selection [of document] has no bearing on the behavior of the .ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior.
document.ready(function($){
// here you go
})

Jquery not working inside of .net project

I have this script referenced inside my main.master file:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js" type="text/javascript"></script>
and inside of my Web User Control I have this jquery but it isnt working, i cant really see where there would be a problem. My code works just fine inside of jsfiddle:
<script type="text/javascript">
$(".package-container").click(function () {
$(this).closest('.radio-group-row').find('.package-title').removeClass('highlight');
$(this).find('input:radio').prop('checked', true);
$(this).find('.package-title').addClass('highlight');
});
</script>
EDIT
My jquery is referenced near the bottom of my master page above the closing body tag.
Make sure your jQuery include is placed early on the page (HEAD element) and either place your code at the end of the body element or wrap it in a DOM ready handler like this:
<script type="text/javascript">
$(function(){
$(".package-container").click(function () {
$(this).closest('.radio-group-row').find('.package-title').removeClass('highlight');
$(this).find('input:radio').prop('checked', true);
$(this).find('.package-title').addClass('highlight');
});
});
</script>
$(function(){YOUR CODE HERE}); is a shortcut for $(document).ready(function(){YOUR CODE HERE});
The advantage of using DOM ready handlers, is that you can place the jQuery code anywhere (including injection by child views/controls).
Update:
If you also need to locally scope your $ variable, I suggest using this rather nice shortcut DOM ready handler. It passes the jQuery instance as a first parameter to the DOM ready function you provide:
jQuery(function($){
// Your code placed here can use $ without any worry about other packages!
});

jQuery not loading at all

I'm trying out jQuery for the first time, and I'm not sure how to make it work properly. I've included the following code near my opening <head> tag:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
Followed by the following jQuery code:
<script>
$('.darkmask > img').hover(function(){
$(this).parent().toggleClass('darkmask-hover');
})​
</script>
Unfortunately, this code doesn't work when I try it in a browser, or in JSFiddle. However, when I set JSFiddle's framework to load jQuery itself, rather than loading jQuery through my own code, the animation works properly.
Am I loading jQuery wrong? If so, what's the right way?
PRoblem is, your code in JSFiddle is executed on the loading on the page. In your code instead, the execution happens when the HTML elements are not yet loaded because it's in the HEAD, so the selectors like .darkmask actually refer to... nothing.
The solution is to use:
$(document).ready(
function()
{
... your code here
}
To ensure that it is executed when the page is loaded and ready, all the HTML elements are there and therefore JQuery selectors can operate on something.
Are there any HTML elements when the code is executed?
Try:
$(function () { // this function executes when the page loads
alert(x);
// put your code here
});
Wrap your entire code in the following:
$(document).ready(function() {
//ALL CODE GOES HERE
});
Wrap your code in:
$(function() {
.... Your code here ...
});
It will mean your code is executed after the DOM tree is loaded.
You do need to wrap your jQuery code within the ready function, like this:
$(document).ready(function(){
// put your code here.
});
Also make sure your script tags have type="text/javascript" as an attribute otherwise it won't get run as javascript.

jQuery not working in external JavaScript

I am new to jQuery and am stuck at some strange issue. I am using jQuery's change and click methods. They are working fine when used in my HTML file in the <script> tag.
Like:
<script>
$("select,input").change(function ()
{
// My code and some alerts
});
</script>
When I copied the same in external JavaScript code without <script> and imported that in my HTML it was not at all working.
Are there any changes which are needed to use jQuery in external JavaScript code?
PS: Some other non-jQuery functions present in same external JavaScript code are successfully called from HTML.
First off, you don't want a <script> tag in an external JavaScript file, if that's how I'm reading your post.
The trick with jQuery is that your code is set to execute immediately.
You want to wrap your script so that it loads when the document is ready, in something like:
$(document).ready(function(){
$("select,input").change(function ()
{
// My code and some alerts
})
});
And you want to make sure that your file is loaded after jQuery (otherwise the $ global will not be set).
Additions:
Here is what your HTML should look like:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jscript/myExternalJs.js"></script>
Here is what your JavaScript code should look like (note there is no script tag inside the JavaScript file):
$(document).ready(function(){
$("select,input").change(function ()
{
// My code and some alerts
})
// Other event handlers.
});
As far as your other script... it sort of depends on what you're doing. The most important thing is to not try to hook event listeners up to objects that don't yet exist, which is why we use document.ready.
Did you make sure jquery is defined before your own jquery code?
You should also make sure the DOM is ready when dealing with jquery:
$(document).ready(function() {
$("select,input").change(function() {
// my code and some alerts
});
// more code here if needed, etc.
});

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>
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(){ });
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.
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).

Categories