0

I've been working on a small project as of late and I'm making a list of items which users can select and purchase, right now the code that I put together displays almost every item from the folder and that lags my browser, therefore I want to make it generate only 5 random images. This is my code:

        var items_folder = "images/items/";
        $.ajax({
            url : items_folder,
            success: function (data) {
                $(data).find("a").attr("href", function (i, val) {
                    if (val.match(/\.(jpe?g|png)$/)) { 
                        $('<li><img src="' + items_folder + val + '" height="80px" width="90px"/></li>').appendTo('#items'); 
                    } 
                });
            }
        });

How would I go about doing this?

Lucas
  • 51
  • 5

1 Answers1

1

You can select five random hrefs with this

var randomHrefs = $(data).find("a").get().sort(function() {
    return Math.round(Math.random()) - 0.5
}).slice(0, 5);

and then iterate through them (in order to display them) with

$(randomHrefs).attr("href", function(i, val) {
    //put your logic here, as in your code
}

this question/answers helped me a lot. Check my simple demo also, it may help.

Community
  • 1
  • 1
Theodore K.
  • 5,058
  • 4
  • 30
  • 46
  • Brilliant! Worked great, thanks for helping out a lad mate, will be looking into your demo now :) – Lucas Jul 05 '16 at 11:54