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
What are jQuery events .load(), .ready(), .unload()?
jQuery load() method
The .load() method is used to attach an event handler to the load event. This event occurs when an element and all its child elements have completely loaded, including images, scripts, and stylesheets.
Example
You can try to run the following code to learn how to work with jQuery .load() method ?
Note: The .load() method was deprecated in jQuery 1.8 and finally removed in jQuery 3.0. To run the following code, add jQuery version lesser than 1.8 ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("img").load(function(){
alert("This is an image.");
});
});
</script>
</head>
<body>
<img src="/videotutorials/images/coding_ground_home.jpg" alt="Coding Ground" width="310" height="270">
<p>This image will load only in jQuery version lesser than 1.8</p>
</body>
</html>
jQuery ready() method
The .ready() method allows you to specify what happens when the DOM (Document Object Model) is fully loaded and ready for JavaScript manipulation, even before images and other resources finish loading.
Example
You can try to run the following code to learn how to work with .ready() method. In this example, we're hiding an element when a button is clicked ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<p>This is demo text.</p>
<button>Hide</button>
</body>
</html>
jQuery unload() method
The .unload() method is used to trigger an event when the user navigates away from the page. This can be useful for cleanup tasks or displaying farewell messages.
Note: The jQuery .unload() method was deprecated in jQuery 1.8 and finally removed in jQuery 3.0. For modern jQuery versions, use the beforeunload event instead.
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(window).unload(function(){
alert("Thanks! Bye!");
});
});
</script>
</head>
<body>
<p>Event triggers when you leave the page.</p>
</body>
</html>
Conclusion
While .load() and .unload() methods have been deprecated and removed from modern jQuery versions, .ready() remains essential for ensuring your JavaScript code executes only after the DOM is fully prepared.
