How to check if an image is loaded with jQuery

To check if an image is loaded successful or not, you can combine the use of jQuery ‘load()‘ and ‘error()‘ event :


$('#image1')
	.load(function(){
		$('#result1').text('Image is loaded!');	
	})
	.error(function(){
		$('#result1').text('Image is not loaded!');
	});

If the image is loaded successful, the load() function is called, otherwise the error() function is called.

Try it yourself


<html>
<head>

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
 
 <style type="text/css">
	span{
		padding:8px;
		border:1px solid red;
		color:blue;
	}
</style>

</head>

<body>

<h1>Check if image is loaded jQuery</h1>
<p>
<img id="image1" 
src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif"/>
<p>Load image from 
"http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif"</p>

<span id="result1"></span>
</p>

<p>
<img id="image2" src="xxxx.jpg"/>
<p>Load image from "xxxx.jpg"</p>

<span id="result2"></span>
</p>

<script type="text/javascript">
		
$('#image1')
	.load(function(){
		$('#result1').text('Image is loaded!');	
	})
	.error(function(){
		$('#result1').text('Image is not loaded!');
	});

$('#image2')
	.load(function(){
		$('#result2').text('Image is loaded!');	
	})
	.error(function(){
		$('#result2').text('Image is not loaded!');
	});
</script>

</body>
</html>

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Pete Manousos Recent comment authors
newest oldest most voted
Pete Manousos
Guest
Pete Manousos

Hi – thanks for the code example on http://www.mkyong.com/jquery/how-to-check-if-an-image-is-loaded-with-jquery/ and we have two questions. 1. Although the “Try Demo” link works as stated (new window opens with URL http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-check-if-image-loaded.html and displays correct results), we noted the span area outlined in red is shrunken and does not appear to contain the load status messages when under the following two circumstances: Save the code locally as test.html via “view source” from the new window that displays after clicking “Try Demo”. Cut/paste code listed under “Try it yourself” into a local file test.html. We note this happens in firefox 10.0.6 and IE 7.0.6022.18005… Read more »