jQuery – Loading random images from directory

1k views Asked by At

jQuery noob here, so apologies for the question!

I'm writing up a static site for a client and they've given me a rather interesting challenge I'm not sure how to approach.

They'd like to have a button on a page that takes random images from a directory and places them in a grid. I'm great with the HTML and the styling, I just have no idea where to get started on the jQuery.

This is basically a demo of what I'd like to implement, assuming the button is pressed every second or so.

Random images button

Is this feasible and/or possible using only jQuery (i.e. having it as a static site)?

Answers accompanied by explanations are greatly appreciated, as I'm still a learner in web dev!

Thanks!

2

There are 2 answers

0
guest271314 On

Try utilizing $.map() , .remove() , setTimeout , .appendTo() , .on()

var updateImages = function updateImages() {
// remove all images from `#container` element having images as child nodes
$("#container img").remove();
// append eight "random" images to `#container`
$.map($.makeArray(Array(8)), function(val, key) {
  setTimeout(function() {
    $("<img />", 
      // image files named "image-0.jpg" - "image-7.jpg" ,
      // `key` : `0` - `7`
      {"src": "/path/to/images/image-" + key + ".jpg"})
    .appendTo("#container");
  }, 1 + Math.floor(Math.random() * 25))
});    
};
// call `updateImages`
$("button").on("click", updateImages);
// set reference to `interval`
// var interval = 0;
// call `updateImages` every `1000` ms
// interval = setInterval(function() {
//  updateImages()
// }, 1000);
0
depperm On

So assuming you have control over the image file names, I would name them like the example you mentioned, image.png. Your js would look like this (I used a table for styling):

$(function(){
    loadRandom();
    $('#clickMe').on('click',function(){
        loadRandom();
    });
});
function loadRandom(){
    var ranNums=[];
    while(ranNums.length<8){
        var t=Math.floor((Math.random()*12)+1);
        if(ranNums.indexOf(t)==-1)
            ranNums.push(t);
    }
    var i=0;
    $('#imageTable > tbody > tr > td > img').each(function(){
        $(this).attr('src','image'+ranNums[i]+'.png');
        i++;
    });
}

And the html, again using a table for styling, would look like

<input type='button' id='clickMe' value='Click Me' />
<table id='imageTable'>
<tr>
    <td><img src=''></td>
    <td><img src=''></td>
    <td><img src=''></td>
    <td><img src=''></td>
</tr>
<tr>
    <td><img src=''></td>
    <td><img src=''></td>
    <td><img src=''></td>
    <td><img src=''></td>
</tr>
</table>