Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Create global variable in jQuery outside document.ready function?
To create a global variable in jQuery that can be accessed outside the document.ready function, you need to declare the variable in the global scope (outside any function) within the <script> tag.
Key Concepts
Global variables in JavaScript are accessible from anywhere in your code. When working with jQuery, you can initialize global variables inside document.ready and use them in other functions.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Global Variable in jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button onclick="checkGlobalVariable()">Check Global Variable</button>
<div id="result"></div>
<script>
// Declare global variable outside document.ready
var globalVariable;
$(document).ready(function() {
// Initialize global variable inside document.ready
function initializeGlobalVariable() {
globalVariable = [{
"name": "John",
"age": 23
}];
}
initializeGlobalVariable();
});
// Function accessible globally that uses the global variable
function checkGlobalVariable() {
if (globalVariable && globalVariable.length) {
var message = 'The Global variable name is: ' + globalVariable[0].name +
', The Global variable age is: ' + globalVariable[0].age;
console.log(message);
$('#result').html('<p>' + message + '</p>');
}
}
</script>
</body>
</html>
How It Works
The global variable is declared outside the document.ready function but initialized inside it. This ensures the variable is available globally while being properly set up when the DOM is ready.
Alternative Approach: Window Object
You can also create global variables using the window object:
<script>
$(document).ready(function() {
// Create global variable using window object
window.globalData = {
users: ["Alice", "Bob", "Charlie"],
count: 3
};
});
function displayGlobalData() {
console.log(window.globalData.users);
console.log("Total users: " + window.globalData.count);
}
</script>
Best Practices
| Method | Pros | Cons |
|---|---|---|
| var declaration | Simple, direct access | Can be accidentally overwritten |
| window object | Explicit global scope | More verbose syntax |
Output
When you click the "Check Global Variable" button, you'll see:
The Global variable name is: John, The Global variable age is: 23
Conclusion
Declare global variables outside document.ready but initialize them inside to ensure proper DOM readiness. Use the window object for explicit global scope when needed.
