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

I want to call the jQuery function from an HTML tag <body>. Here is my HTML:

< body bgcolor="#ffffff" onLoad="???" >

How can I call the jQuery function when the page loads? My jQuery function looks like this:

jQuery(function($){
    var input_id;
    //code
});
+4
source share
6 answers

any code that you write in the method below (block) will be executed automatically after loading the DOM. You do not need to call this again from the HTML component.

 $(document).ready(function() { 

//your code
});
+10
source

This section has been reviewed here earlier.

You are most likely looking

$(document).ready(function() { 
    var input_id;
    //code
})

or

$(window).load(function($) {
    var input_id;
    //code
});

If you are interested in learning about the differences between the two, see the jQuery documentation on this topic.

, <body onload="">, , JQuery.

+3

HTML: ,, JS body. . JS :

<body bgcolor="#ffffff">

JS

$(window).load(function($) {
    functionA(arg1, arg2, arg3);
});

functionA() DOM, .

$(document).ready(function($) {
    functionA(arg1, arg2, arg3);
});

functionA() DOM .

+2
$(function() {
    // code
});

document.ready(), .

+2

JQuery 3, :

document.ready(function(){
   //code
});

The recommended alternative in JQuery 3 is to use the following syntax (which in previous versions was considered a shorthand syntax):

$(function(){
    //code
});

Here is the official Jquery explanation of why the first syntax was discounted and no longer recommended ( https://api.jquery.com/ready/ ):

... The selection of [document] does not affect the behavior of the .ready () method, which is inefficient and can lead to incorrect assumptions about the behavior of the method.

0
source
document.ready(function($){
  // here you go
})
-1
source

All Articles