Everytime the page loads, I want to display the items in my Projects node in a random order, with varying sizes as well.
So, I know how to access one item randomly as so:
var i = 0;
var rand = Math.floor(Math.random() * snapshot.numChildren());
snapshot.forEach(function(snapshot) {
if (i == rand) {
// picked random item, snapshot.val().
}
i++;
});
but I don't know how to do it multiple times for multiple items. I came up with this:
var numItemsPerLoad = 3;
for(var i = 0; i < numItemsPerLoad; i++){
ref.limitToFirst(numItemsPerLoad).on("value", function(snapshot){
var rand = Math.floor(Math.random() * snapshot.numChildren());
var j = 0;
snapshot.forEach(function(snapshot){
var li = document.createElement("li");
var img = document.createElement("img");
var iframe = document.createElement("iframe");
if(j == rand){
img.setAttribute("src", snapshot.val().url);
//These commented ones will randomize the height and width, but it'll look stretched and ugly sometimes
//img.setAttribute("width", randomNum(100, 250));
//img.setAttribute("height", randomNum(100, 250));
li.appendChild(img);
ul.appendChild(li);
}
j++;
});//end snapshot forEach
});
But when I do it like this, where I try to randomly choose an item three separate times, it might choose an item it chose before, so it'd display the same item twice or thrice even. Is there a better/more efficient way to randomly display ALL the items in a node?
Aucun commentaire:
Enregistrer un commentaire