1
votes

I have a list of products, and in each li element with jquery I want to show the image in the attribute data-thumb in the img within in the li element. i.e. set the value of img src to the value of data-thumb in each li element, but while it is loading I want to show ajax-loader.gif that is already there. Could someone lead me in the right direction?

example:

<li data-id="7" data-thumb="http://test.com/assets/pdc/thumbs/66.png" data-img="http://test.com/assets/pdc/img/66.png" data-country="Australia" data-company="Big Farm" data-app="Tea" data-brand="Big Farm" data-package="500" class="product air-500 cat7">
    <img class="tip" data-country="Australia" data-brand="Big Farm" src="assets/img/ajax-loader.gif">
</li>

Thanks!

2

2 Answers

3
votes

Try this:

// Loop through all lis with class product
$('li.product').each(function(){
    // grab a reference to the current li
    var $el = $(this);
    // get the url from its data-thumb attribute
    var url = $el.data('thumb');
    // create a new Image element to load into
    var img = new Image();
    // load callback for the new image
    img.onload = function() {
        // find the first image inside the li
        // and change its src to the url we just loaded
        $el.find('img')[0].src = url;
    }
    // set the src of our temp Image to start loading
    img.src = url;
});

The idea behind the code is, create a new Image element that is not appended to the DOM, and load your url into it. When it's loaded, replace the inner <img> url. So the spinner should show while the image is being loaded, then it should be replaced with the actual image (now loaded from the browser's cache).

0
votes

You could do

$('li.product').each(function() {
    var $this = $(this);
    $this.find("img").attr("src", $this.data("thumb"))
});