Pradyut Bhattacharya
Pradyut Bhattacharya

Reputation: 5748

image loading information with jquery

I have a page which has a img holder with the html: -

<img src="someimage.jpeg" alt="image" class="show_image"/>

Now i m updating the image with jquery using the code...

$('.show_image').attr('src', 'anotherimage.jpeg');

Now its working fine but i want to show the users the image is being loaded and may wait

as the image size may be huge...

Is there any method in jquery to get the information of percent loaded(bytes read/remaining)

or if the image load is complete...

Also how can i place a div over the image placeholder such that the

div can fade the image(opacity:0.8) and add some text over the div as loading or something

thanks

Upvotes: 0

Views: 1369

Answers (2)

ehsun7b
ehsun7b

Reputation: 4866

As far as I know this kind of info should be provided by the browser and now you can just get notified when the loading is finished by means of OnLoad attribute of img tag. But you can not get the precise amount of downloaded data, I think.

I suggest you to change your code like this:

<img src="someimage.jpeg" alt="image" class="show_image"/>

$('.show_image').attr('src', 'tiny.gif'); // a very small gif animation as loading indicator

$('.show_image').attr('src', 'anotherimage.jpeg');

Another solution is to preload the big image like this:

<html>
<head>
 <script type='text/javascript'>
   var image = new Image();
   image.src = "anotherimage.jpeg";
 </script>
</head>
<body>
 <img src="someimage.jpeg" alt="image" class="show_image"/>
 <script type='text/javascript'>
   $('.show_image').src = image.src; // no delay for loading happens
 </script>     
</html>
</body>

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382841

You can do something like this:

// change image
$('.show_image').attr('src', 'anotherimage.jpeg');
// image is loading
$('#divID').html('Image is being loaded....');

// image loaded
$('.show_image').load(function(){
  // hide/remove the message
  $('#divID').html('');
});

You assign load event to the image which fires when image has finished loading. Before that, you can show your message/progress/loader.

Upvotes: 3

Related Questions