Preload image and show counter when loading

Hy,

I am using uploadify to upload some images, after I display all the previews of the images in the list when I click on the thumb image of the larger image it opens in a div with this function

$(".thumbs li a").click(function(){
    var largePath = $(this).attr("href");
    $('.thumbs li').removeClass('thumbac');
    $(this).parent().addClass('thumbac');
    $("#largeImg").attr({ src: largePath });
    return false;
});

      

here is my list of photos:

<div class="upimage">
  <ul id="upimagesQueue" class="thumbs">
    <li id="liupimages">
      <a href="uploads/0001.jpg"><img src="uploads/0001.jpg" alt="0001.jpg" id=""></a>
    </li>
    <li id="liupimages">
      <a href="uploads/0002.jpg"><img src="uploads/0002.jpg" alt="0002.jpg" id=""></a>
    </li>
    <li id="liupimages">
      <a href="uploads/0003.jpg"><img src="uploads/0003.jpg" alt="0003.jpg" id=""></a>
    </li>
<script>
$(".thumbs li a").click(function(){
    var largePath = $(this).attr("href");
    $('.thumbs li').removeClass('thumbac');
    $(this).parent().addClass('thumbac');
    $("#largeImg").attr({ src: largePath });
    return false;
});
</script>
  </ul>
</div>

      

this is the div where the images are displayed

<div class="largeImg" >     
    <img id="largeImg" src="" />
</div>

      

how can I preload an image before displaying it?

+2


a source to share


3 answers


You can use the load

event in some way , for example:



$(".thumbs li a").click(function(){
    var largePath = $(this).attr("href");
    $('.thumbs li').removeClass('thumbac');
    $(this).parent().addClass('thumbac');
    $("#largeImg").hide()
                  .attr({ src: largePath })
                  .load(function() {
                       $(this).show();
                   });
    return false;
});

      

+3


a source


this is how you can preload images in jq:

    (function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

      



and then you preload them like this:

jQuery.preLoadImages("image1.gif", "/path/to/image2.png");

      

0


a source


You can use my imgPreload plugin which displays a nice counter when preloading an image.

In your case, you just need to add one line to your existing code:

$("#largeImg").attr({ src: largePath }); //your code
$("#largeImg").imgPreload() //the extra line

      

Please see this page http://denysonique.github.com/imgPreload/ for demo and documentation.

0


a source







All Articles