Unsorted list: download images or sections on demand

I made a horizontal slider using iScroll.

I want to display a lot of images (or divs) and I added these images like this:

<ul>
<li style="background: url(fotos/PabloskiMarzo2008.jpg) no-repeat;  background-size: 100%; -moz-background-size: 100%; -o-background-size: 100%; -webkit-background-size: 100%; -khtml-background-size: 100%;  "></li>
...
<ul>

      

But it takes a long time for each image to load (I'm going to use an image map or divs instead of images).

How can I upload images on demand? When the user clicks to the left, I want to load the next image.

+1


source to share


1 answer


//setup list of images to lazy-load, also setup variable to store current index in the array
var listOfImages = ['fotos/zero.jpg', 'fotos/one.jpg', 'fotos/infinity.jpg'],
    imageIndex   = 0,
    myScroll     = new iScroll('my-element');

//bind to the swipeleft event on the list
$('ul').bind('swipeleft', function () {

    //append a new list-item to the list, using the `listOfImages` array to get the next source
    //notice the `++` that increments the `imageIndex` variable
    $(this).append($('li', { style : 'background: url(' + listOfImages[imageIndex++] + ') no-repeat;  background-size: 100%; -moz-background-size: 100%; -o-background-size: 100%; -webkit-background-size: 100%; -khtml-background-size: 100%;' }));

    //since the dimensions of your scroller have changed, you have to let iScroll know
    myScroll.refresh();
});

      

You can also place most of this CSS in a class that affects elements, so you don't have to add it to the line for every element:

JS -



    $(this).append($('li', { style : 'background-image : url(' + listOfImages[imageIndex++] + ')' }));

      

CSS -

#my-element li {
    background-repeat       : no-repeat;
    background-size         : 100%;
    -moz-background-size    : 100%;
    -o-background-size      : 100%; 
    -webkit-background-size : 100%;
    -khtml-background-size  : 100%;
}

      

+1


source







All Articles