Welcome to the jQuery Document Ready tutorial! In this lesson, we'll explore how to ensure your JavaScript code runs only when the DOM (Document Object Model) is fully loaded, making your web pages more responsive and user-friendly.
Let's start by understanding why the Document Ready concept is important 📝:
To work with jQuery, you'll first need to include the library in your HTML file. Add the following code within the <head> section:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>Once you have jQuery installed, you can use the $(document).ready() function to define the code that should run when the DOM is ready.
The $(document).ready() function wraps your code in a self-executing anonymous function, which ensures it's only invoked once the DOM is ready. Here's an example:
$(document).ready(function() {
// Your code here
});Replace // Your code here with the JavaScript you want to execute when the DOM is ready.
Suppose we have an image that takes some time to load, and we want to add a message indicating that the image is loading. With the Document Ready technique, we can ensure that our message is displayed only after the image has finished loading.
Here's a complete example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Document Ready Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>jQuery Document Ready Example</h1>
<img id="myImage" src="big-image.jpg" alt="A big image">
<div id="loadingMessage">Loading image, please wait...</div>
<script>
$(document).ready(function() {
// Hide the loading message initially
$('#loadingMessage').hide();
// Show the loading message when the image is not loaded yet
$('#myImage').on('load', function() {
$('#loadingMessage').show();
});
});
</script>
</body>
</html>In this example, we first hide the loading message using $('#loadingMessage').hide(). Then, we use the .on('load') method to attach a function that shows the loading message when the image is fully loaded.
Question: What does the $(document).ready() function do in jQuery?
A: It makes your web pages faster and more responsive B: It ensures that your JavaScript code runs only when the DOM is fully loaded C: It speeds up the loading of images on your web pages
Correct: B
Explanation: The $(document).ready() function ensures that your JavaScript code runs only when the DOM is fully loaded, making your web pages more responsive and user-friendly.