In jQuery, the $(document).ready() function is used to execute code when the DOM (Document Object Model) is fully loaded and ready to be manipulated. It ensures that your jQuery code runs after the HTML document has been parsed and is ready for interaction.
Here's an example to illustrate the use of $(document).ready():
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Ready Function Example</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<!-- Your HTML content -->
<script>
// This code will run when the DOM is fully loaded and ready
$(document).ready(function () {
// Your jQuery code goes here
// Example: Change the text of an element
$('#exampleElement').text('DOM is ready!');
// Example: Attach a click event handler to a button
$('#exampleButton').click(function () {
alert('Button clicked!');
});
});
</script>
<!-- Your HTML content -->
</body>
</html>
In this example:
The jQuery library is included in the <head> section.
Inside the <body> section, there's a <script> block that contains your jQuery code.
The $(document).ready(function () { ... }) function is used to encapsulate the jQuery code that should run when the DOM is ready.
Inside the $(document).ready() function, you can include any jQuery code you want to execute once the DOM is ready. This is a good practice to ensure that your code won't run until the HTML document is fully loaded.
It's worth noting that a shorthand for $(document).ready() is
$(function() {...}). Both notations are equivalent, and you can use either based on your preference.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In jQuery, the $(document).ready() function is used to execute code when the DOM (Document Object Model) is fully loaded and ready to be manipulated. It ensures that your jQuery code runs after the HTML document has been parsed and is ready for interaction.
Here's an example to illustrate the use of $(document).ready():
In this example:
Inside the $(document).ready() function, you can include any jQuery code you want to execute once the DOM is ready. This is a good practice to ensure that your code won't run until the HTML document is fully loaded.
It's worth noting that a shorthand for $(document).ready() is $(function() {...}). Both notations are equivalent, and you can use either based on your preference.