JackArrgon
JackArrgon

Reputation: 127

Random element from an array of images and their respective links on page refresh

I've got an unordered list of images. I'd like for each of those images to have an href attribute (since I would like to use a lightbox-popup to display the correlating image when clicked), but for each image to be random when the page is refreshed.

In short, for each image coupled with its href to be random, but the order of the ul to stay the same. What would be a way of achieving this?

Upvotes: 1

Views: 320

Answers (2)

Seimen
Seimen

Reputation: 7250

Hopefully I get this right.

With jQuery you could do it like this jsfiddle:

$('ul').children('li').sort(function() {
    return Math.round(Math.random()); // randomly get 0 or 1
}).appendTo('ul');

Doing it with PHP on server side would make more sense, but since you have no db resource or so, you'd have to make a static array of image:link pairs then shuffle it and generate a random list.

UPDATE

Maybe this comes closer to a solution:

jsfiddle

var contents = new Array(),
    $list = $('li');

$list.each(function() { contents.push($(this).children()); });

contents.sort(function() {
    return 0.5 - Math.random();
});

$list.each(function() {
    $(this).append(contents.shift());
});

Upvotes: 0

Geuis
Geuis

Reputation: 42297

var img_array = []; //assuming your array is called this and full of porn pictures

//fisher-yates algorithm. Google it
(function(){
    var tmp, current, top = img_array.length;
    if(top) while(--top) {
        current = Math.floor(Math.random() * (top + 1));
        tmp = img_array[current];
        img_array[current] = img_array[top];
        img_array[top] = tmp;
    }
})();

//target html element where the images are appended
var target = document.getElementById('someTargetDiv');

for(var i=0, len=img_array.length; i<len; i++){
    var link = document.createElement('a'),
        img = document.createElement('img');

    link.setAttribute('href', img_array[i]);
    img.setAttribute('src', img_array[i]);

    link.appendChild(img);
    target.appendChild(link);
}

This is not an optimized way of doing this kind of operation. I've made it slightly more verbose for your understanding.

The biggest mistake with this code is the constant creation of many different elements and appending them to the DOM one at a time. What should really be done is to build a string of generated html, and changing the innerHTML of a target div in one operation.

var html = [];
for(var i=0, len=img_array.length; i<len; i++){
    html.push('<a href="'+ img_array[i] +'"><img src="'+ img_array[i] +'"></a>');
}

target.innerHTML = html.join('');

Upvotes: 2

Related Questions