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
Is it possible to detect when images are loaded via a jQuery event?
To detect loading of an image with jQuery, use the load() event handler.
Note: The load() method was deprecated in jQuery version 1.8 and completely removed in version 3.0. To see its working, you need to use jQuery version before 3.0.
Using load() Event Handler
The load() event is fired when an image has finished loading completely. This event can be attached to image elements to execute code once the image is fully loaded in the browser.
Example
You can try to run the following code to learn how to detect when image loads ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("img").load(function(){
alert("Image successfully loaded.");
});
});
</script>
</head>
<body>
<img src="/videotutorials/images/tutor_connect_home.jpg" alt="Tutor" width="304" height="236">
</body>
</html>
The output of the above code is ?
When the image loads completely, an alert box will appear with the message "Image successfully loaded."
Modern Alternative
For modern jQuery versions (3.0+), you can use the on() method with the 'load' event instead ?
$(document).ready(function(){
$("img").on('load', function(){
console.log("Image loaded successfully");
});
});
Conclusion
While the load() method was useful for detecting image loading in older jQuery versions, modern applications should use the on('load') approach for better compatibility with current jQuery versions.
