开发者

Determining if a changed image is loaded

I am creating a little gallery using jQuery and stuck on a small point

it's something like this:

<script type="text/javascript">
$(document).ready(function(){
$('#thumb1').click(function(){
          $('#fullimage').attr('src','loading.gif').fadeOut(800,function(){
            $(this).attr('src','newimage.jpg').bind('onreadystatechange load', function(){
            $(this).fadeIn(300);       
            });

          });          
       });
//same code for $('#thumb2') etc.
});
</script>
<img src="defaultimage.jpg" id="fullimage" /><br />
<a><img id="thumb1" src="notimportantthumb.jpg"></a>
<a><img id="thumb2" src="notimportantthumb2.jpg"></a>

The thing is that, if the loading of the image takes more than 800ms, it won't work.

I know I have to use jQuery's load() or similar function, but I could not put it together. How can I identify if a changed image with jQuery is loaded or not ? Thanks

Edit: Solved with adding a second hidden image as a loader. If anyone's interested:

<script type="text/javascript">
    $(document).ready(function(){
    $('#thumb1').click(function(){
        if ($('#fullimage').attr('src')!='newimage.jpg') { //it would not load, just show the loading.gif

            $('#fu开发者_运维问答llimage').hide(); $('#hiddenloader').show();
              $('#fullimage').attr('src','newimage.jpg').load(function(){
                $('#hiddenloader').fadeOut(300,function(){
                    $('#fullimage').fadeIn(300);
                });

                });

          }
    });
//same code for $('#thumb2') etc.
});
</script>
<img src="defaultimage.jpg" id="fullimage" /><br />
<img src="loading.gif" id="hiddenloader" style="display: none;" />
<a><img id="thumb1" src="notimportantthumb.jpg" /></a>
<a><img id="thumb2" src="notimportantthumb2.jpg" /></a>


the onload event should fire any time the src attribute changes and the image finishes loading

Edit for code sample:

$('#thumb1').click(function(){
    $('#fullimage').attr('src','loading.gif').fadeOut(800,function(){
            $(this).attr('src','newimage.jpg').load(function(){
            $(this).fadeIn(300);       
        });
    });          
});

Though I will say that this method of presenting a loader image is slightly unusual.


Can you preload the images on load.

http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜