lundi 11 juillet 2016

Take a random n number array of elements and insert them in a specified element

I have a list of books that are embedded frame elements. I'm wanting to return three of those books and insert them into a div I've already defined. I'm trying to utilize the shuffle method, but something isn't going right as I can't get the elements to display or randomize.

The code below is the example I'm trying to work with.

Javascript

   function randomBooks(arr, count) {

   var arr = [ // list of books
   '<iframe type="text/html" width="150" height="200" frameborder="0" allowfullscreen style="max-width:100%" src="http://ift.tt/29JAuxz" ></iframe>',
   '<iframe type="text/html" width="150" height="200" frameborder="0" allowfullscreen style="max-width:100%" src="http://ift.tt/29L3QZp" ></iframe>',
   '<iframe type="text/html" width="150" height="200" frameborder="0" allowfullscreen style="max-width:100%" src="http://ift.tt/29JB9yQ" ></iframe>',
   '<iframe type="text/html" width="150" height="200" frameborder="0" allowfullscreen style="max-width:100%" src="http://ift.tt/29JAuxz" ></iframe>',
   '<iframe type="text/html" width="150" height="200" frameborder="0" allowfullscreen style="max-width:100%" src="http://ift.tt/29L3QZp" ></iframe>',
   '<iframe type="text/html" width="150" height="200" frameborder="0" allowfullscreen style="max-width:100%" src="http://ift.tt/29JB9yQ" ></iframe>'

   ];    

   var insertDiv = document.getElementsByClassName("bookFrame"); // Div I want elements inserted

   var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
   while (i-- > min) {
       index = Math.floor((i + 1) * Math.random());
       temp = shuffled[index];
       shuffled[index] = shuffled[i];
       shuffled[i] = temp;
   }

   var returnedValue= shuffled.slice(min, 3);
   insertDiv.innerHTML(returnedValue); // inject 3 random book elements

   alert( randomBooks(arr, 3)); // Checking 

   };

HTML

<p class="center bookFrame">

<!-- Insert books here -->

</p>




Aucun commentaire:

Enregistrer un commentaire