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

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
})

Related

How to wait to execute JS until readyState == Complete for document and window? [duplicate]

I need to execute some JavaScript code when the page has fully loaded. This includes things like images.
I know you can check if the DOM is ready, but I don’t know if this is the same as when the page is fully loaded.
That's called load. It came waaaaay before DOM ready was around, and DOM ready was actually created for the exact reason that load waited on images.
window.addEventListener('load', function () {
alert("It's loaded!")
})
For completeness sake, you might also want to bind it to DOMContentLoaded, which is now widely supported
document.addEventListener("DOMContentLoaded", function(event){
// your code here
});
More info: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
Usually you can use window.onload, but you may notice that recent browsers don't fire window.onload when you use the back/forward history buttons.
Some people suggest weird contortions to work around this problem, but really if you just make a window.onunload handler (even one that doesn't do anything), this caching behavior will be disabled in all browsers. The MDN documents this "feature" pretty well, but for some reason there are still people using setInterval and other weird hacks.
Some versions of Opera have a bug that can be worked around by adding the following somewhere in your page:
<script>history.navigationMode = 'compatible';</script>
If you're just trying to get a javascript function called once per-view (and not necessarily after the DOM is finished loading), you can do something like this:
<img src="javascript:location.href='javascript:yourFunction();';">
For example, I use this trick to preload a very large file into the cache on a loading screen:
<img src="bigfile"
onload="this.location.href='javascript:location.href=\'javascript:doredir();\';';doredir();">
Try this it Only Run After Entire Page Has Loaded
By Javascript
window.onload = function(){
// code goes here
};
By Jquery
$(window).bind("load", function() {
// code goes here
});
Try this code
document.onreadystatechange = function () {
if (document.readyState == "complete") {
initApplication();
}
}
visit https://developer.mozilla.org/en-US/docs/DOM/document.readyState for more details
Javascript using the onLoad() event, will wait for the page to be loaded before executing.
<body onload="somecode();" >
If you're using the jQuery framework's document ready function the code will load as soon as the DOM is loaded and before the page contents are loaded:
$(document).ready(function() {
// jQuery code goes here
});
the window.onload event will fire when everything is loaded, including images etc.
You would want to check the DOM ready status if you wanted your js code to execute as early as possible, but you still need to access DOM elements.
You may want to use window.onload, as the docs indicate that it's not fired until both the DOM is ready and ALL of the other assets in the page (images, etc.) are loaded.
In modern browsers with modern javascript (>= 2015) you can add type="module" to your script tag, and everything inside that script will execute after whole page loads. e.g:
<script type="module">
alert("runs after") // Whole page loads before this line execute
</script>
<script>
alert("runs before")
</script>
also older browsers will understand nomodule attribute. Something like this:
<script nomodule>
alert("tuns after")
</script>
For more information you can visit javascript.info.
And here's a way to do it with PrototypeJS:
Event.observe(window, 'load', function(event) {
// Do stuff
});
The onload property of the GlobalEventHandlers mixin is an event
handler for the load event of a Window, XMLHttpRequest, element,
etc., which fires when the resource has loaded.
So basically javascript already has onload method on window which get executed which page fully loaded including images...
You can do something:
var spinner = true;
window.onload = function() {
//whatever you like to do now, for example hide the spinner in this case
spinner = false;
};
Completing the answers from #Matchu and #abSiddique.
This:
window.addEventListener('load', (event) => {
console.log('page is fully loaded');
});
Is the same as this but using the onload event handler property:
window.onload = (event) => {
console.log('page is fully loaded');
};
Source:
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
Live example here:
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event#live_example
If you need to use many onload use $(window).load instead (jQuery):
$(window).load(function() {
//code
});
2019 update: This is was the answer that worked for me. As I needed multiple ajax requests to fire and return data first to count the list items.
$(document).ajaxComplete(function(){
alert("Everything is ready now!");
});

Manipulation of DOM by JavaScript execution order

I have the following code and results is attached at the end. I understand that JQuery.ready and JQuery.Window load events are run after the DOM is created so it can manipulate the DOM but not the first function to change the background of John.
My questions are:
The background of John has not changed to yellow is because JavaScript is backward referencing by nature and it can't locate the element with the id name1 at the point when the script is run?
If I have to run the first function to change the background of John, should this function be used after the DIV tags?
Blockquote
<script>
(function () {
$('#name1').css('background-color', 'yellow');
})();
$(function () {
$('#name2').css('background-color', 'red');
});
$(window).load((function () {
$('#name3').css('background-color', 'blue');
}));
</script>
<div id="name1">John</div>
<div id="name2">Mary</div>
<div id="name3">Jacob</div>
<div id="name4">James</div>
<script>
(function () {
$('#name4').css('background-color', 'yellow');
})();
</script>
Blockquote
HTML gets read by the browser from top to bottom. So:
<script>
this gets executed immediately: (but as nothing is there yet, there will be no change). To further explain, these are called immediate executed functions (IEFs) ==> (function(){ ... })(); but in this case is pointless to have it because the code will be executed immediately anyway.
(function () {
$('#name1').css('background-color', 'yellow');
})();
this is actually a shortcut in jQuery for $(document).ready(...); It is consider not such a good practice because it is not as readable.
$(function () {
$('#name2').css('background-color', 'red');
});
this one does a window load (which is not exactly the same).
$(window).load((function () {
$('#name3').css('background-color', 'blue');
}));
</script>
<div id="name1">John</div>
<div id="name2">Mary</div>
<div id="name3">Jacob</div>
<div id="name4">James</div>
<script>
this is also executed immediately (IEFs): in this case it will work but it is not a best practice to do this.
(function () {
$('#name4').css('background-color', 'yellow');
})();
</script>
if you want to know more of the differences between document.ready and window.load, look at this stackoverflow question
JavaScript is an event driven language, and the advantage is that you can add as many listeners to events as you need, so adding an event listener to DOM content loaded would be —almost— always the best approach. It is also a best practice to load the scripts always at the end, this way you let the user get the content and styles first and then the functionality kicks in.
How I would have written your code:
<div id="name1">John</div>
<div id="name2">Mary</div>
<div id="name3">Jacob</div>
<div id="name4">James</div>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
// DOM fully loaded and parsed
$('#name1').css('background-color', 'yellow');
$('#name2').css('background-color', 'red');
$('#name3').css('background-color', 'blue');
$('#name4').css('background-color', 'yellow');
});
</script>
Although I wouldn't have used jQuery for this :P. I wouldn't even have used JavaScript for this, just good old CSS ;)
When manipulating the DOM via Javascript (or a Javascript library or framework) you must bring those elements of the DOM you want to manipulate into existence before you attempt to manipulate them.
If you don't, then... there is simply nothing there to manipulate.

Attach script to jQuery ready method before jQuery is loaded

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/

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.

weird jQuery JSON function... whats going on here?

Im browsing the flot examples here http://people.iola.dk/olau/flot/examples/turning-series.html
(view source once there)
I came across this :
<script id="source" language="javascript" type="text/javascript">
$(function () {
var datasets = {
"usa": {...
The $(function() part. I get that its an anonymous function, I dont get why it is used here. Wouldnt this be just as good :
<script id="source" language="javascript" type="text/javascript">
var datasets = {
"usa": {...
I checked over at the jQuery docs (http://api.jquery.com/) and found no special use for function()
$(function () {
Is for executing the code when the DOM is ready, it's a document.ready handler in jQuery, the same effect as:
$(document).ready(function () {
You want to run certain things on document.ready so that the elements are there, for example if you're using $(".class") as a selector, you wouldn't want that code to run until the DOM was fully loaded, so the elements you're looking for are there, ready to be found by the selector...this means your code would always work, even if it's in the <head>.
For documentation, look at jQuery(callback) in the API.
This is shorthand for $(document).ready(handler) which waits until the DOM is fully loaded before running the anonymous function.
In jQuery, $(function() { is shorthand for $(document).ready(function() {.
Yes, your 2nd part would work equally well, but the first one guarantees that the entire DOM for the page is loaded before it is executed.

Categories