Choose an array containing a random set of n elements and place them into a designated element

I am working on a project where I have a collection of books embedded as iframe elements. My goal is to select three random books from this list and display them within a pre-defined div. However, despite my attempts to use the shuffle method, I am encountering issues with displaying or randomizing the elements.

Below is an example of the code snippet I am currently working with:

Javascript

   function getRandomBooks(arr, count) {

   var arr = [ // List of embedded book iframes
   '<iframe type="text/html" width="150" height="200" frameborder="0" allowfullscreen style="max-width:100%" src="https://read.amazon.com/kp/card?asin=B00ARFNQ54&asin=B00ARFNQ54&preview=newtab&linkCode=kpe&ref_=cm_sw_r_kb_dp_wpdGxbH9ZAXX9&hideShare=true" ></iframe>',
   ... (remaining array entries omitted for brevity)

   ];    

   var insertDiv = document.getElementsByClassName("bookFrame"); // Target div for inserting elements

   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 selectedBooks = shuffled.slice(min, 3);
   insertDiv.innerHTML(selectedBooks); // Insert 3 randomly selected books into the designated div

   alert(getRandomBooks(arr, 3)); // Test call 

   };

HTML

<p class="center bookFrame">

<!-- Random books will be inserted here -->

</p>

Answer №1

There seems to be a number of mistakes in this code.

To start, the

alert( randomBooks(arr, 3)); // Checking
is placed within the function randomBooks itself, meaning it will never be triggered.

Additionally, using

insertDiv.innerHTML(returnedValue);
is incorrect as 'innerHTML' is not a function but a string. Furthermore, getElementsByClassName returns a list rather than a single element, so the correct syntax should be:

insertDiv[0].innerHTML = returnedValue;

It appears there may be more errors present since the code does not seem to have been executed yet. It would be beneficial to run the code and observe its behavior first.

A helpful suggestion: for testing purposes, instead of modifying the code with random calls and alerts, you can use the developer console (accessible by pressing F12 in Chrome) to call randomBooks() directly and view its output.

Answer №2

There could have been several reasons why things weren't working as expected. It seems that there were multiple minor errors in the code.

The randomBooks() method was supposed to accept an argument named arr, but it appears that you replaced it with your own array. Perhaps you intended to pass the array of books into the randomizer function, which I have done in my example.

Another issue is that getElementsByClassName() returns an array. You may need to extract the first element from the array or consider using querySelector() if you specifically require the first matching element.

Lastly, assigning directly to el.innerHTML is not correct. It seems like you meant to use it similar to jQuery's $el.html() method.

function addBooks(target, bookIds, count) {
  // -----------------------------
  // A classic array shuffler (inplace).
  // -----------------------------
  function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
      var j = Math.floor(Math.random() * (i + 1));
      var temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array;
  }
  // -----------------------------

  // -----------------------------
  // Get 3 random books.
  // -----------------------------
  shuffleArray(bookIds);
  var selected = bookIds.slice(0, 3);
  // -----------------------------
  
  // -----------------------------
  // Construct some HTML for the 3 books.
  // -----------------------------
  var html = selected.map(function(bookId){
    var retval = '<iframe type="text/html" frameborder="0" allowfullscreen src="https://read.amazon.com/kp/card?asin=' + bookId + '&asin=' + bookId + '&preview=newtab&linkCode=kpe&ref_=cm_sw_r_kb_dp_wpdGxbH9ZAXX9&hideShare=true" ></iframe>';
    return retval;
  });
  // -----------------------------

  // -----------------------------
  // inject 3 random book elements
  // -----------------------------
  document.querySelector(target).innerHTML = html;
  // -----------------------------
};

var bookIds = [
  'B00ARFNQ54',
  'B00AFH1TBC',
  'B005GSYZRA',
  'B00ARFNQ54',
  'B00AFH1TBC',
  'B005GSYZRA'
];

addBooks(".bookFrame", bookIds, 3);
iframe { width: 150px; height: 200px; max-width:100%; }
<p class="center bookFrame"><!-- Insert books here --></p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered Runtime Issue of TypeError: undefined cannot be iterated (unable to access property Symbol(Symbol.iterator))

I've been working on a multiselect feature in my Next.js project, utilizing states and setting them accordingly. However, I keep encountering this specific error: https://i.stack.imgur.com/m8zuP.png whenever I click on this: https://i.stack.imgur.c ...

Implementing a watcher property in JavaScript to dynamically add a class to an element

I'm currently facing an issue where I need to apply a class to an element when a certain data property changes. My approach involves using a watcher to monitor the value change and adding a class through JavaScript, as demonstrated in the code snippet ...

Issues with $.getjson and trouble with storing JSON data

My current issue involves attempting a getJSON call to a page on my domain that contains a simple JSON array. However, the script in my webpage is not returning anything as expected. <script> $('#genButton').click(function() { ...

How can we arrange a two-dimensional array in descending order of string length using the first string in the sub-array as the basis for

If I have an array with elements like these: var array = [["This should be last", 1], ["This should be first I think", 1], ["This is the middle one", 1]]; The second value in each sub-array, which is always 1 in this case, doesn ...

"Encountered an unexpected token in Javascript - jsp error

Recently, I started working on a JSP application and encountered an issue with passing URL variables from a servlet to a JSP page using request.getattribute. When trying to pass the data to a JavaScript function, we received the following error: Uncaught ...

Using JSDoc, consider a Plain Old JavaScript Object (POJO) as an instance

When working with a class and a function that accepts an instance of that class or a similar POJO object, there is a desire to use JSDoc annotations. class Example { constructor(x, y) { this.x = x; this.y = y; } } /** * @param {E ...

Implementing a feature in React where the active class is applied only to the next element upon clicking

I'm just starting out with React and working on a custom menu bar project. The Mobile menu includes 2 dropdown submenus, which I want to toggle open and close by clicking an arrow. Currently, the arrows are functioning, but when I click on one arrow, ...

Problem with vueJS List Transition not being triggered

Within my Vue JS App, I encountered a situation where I have a list of items that change order randomly when the user clicks a button. Despite successfully using Vue.set to dynamically reposition the list elements, I faced an issue with adding a transition ...

Connect the input field to a dictionary

Here is an input field: <input id="DeviceId" class="form-control deviceCatalog" data-bind="value:DeviceTemp, valueUpdate: ['blur']" required /> This input is connected to the following viewModel: var ViewModel = f ...

mention the element to display on the pagination

I find the logic here quite puzzling. This particular code block seems to be related to pagination, as it involves a function that is triggered upon clicking. componentDidUpdate() { const { location } = this.context; const { query } = this; if ...

express.js does not properly support the app.get functionality

app.get('/:id', function (req, res){ UserModel.find({ user: req.params.id}, function (err, user){ if (err) throw err; console.log(user + '\n\n'); res.render('profile.ejs', { ...

Looking to replace a background image using javascript?

(apologies for any language mistakes) I have multiple divs with a common background image. I assigned them the same class and set the background image using CSS in style.css which worked perfectly fine. Now, I want to change the background image dynamical ...

Is there a way in Selenium to determine the type of tag associated with the element we are trying to locate?

Is there a way in Selenium to determine the type of tag? On my automation page, some fields may change their type. For example, if the first field value is greater, the second field becomes an input text; if the first is "IN", then a dropdown appears. So, ...

Heroku experiences unexpected surge in memory consumption while using Puppeteer

Yesterday, a commit caused the process to hit Heroku's memory limit resulting in an R15 error. The code worked perfectly during testing and on Heroku until it reached a certain number of checked items, triggering the error. What's intriguing is t ...

How to align scrolling images with their scroll origin - a step by step guide

Curious to know the name of the effect where images scroll in a different orientation than the page, creating a 2D appearance. Take a look at the Google Nexus website and scroll down - do you see the effect? What is this effect called? Is it created usin ...

What is the best way to implement collision detection using raycasting?

For my university project, I am looking to implement collision similar to what is shown in this example. However, I am facing an issue where collision is only working on the top of the object. I referred to this for guidance. My goal is to add collision to ...

The memory allocation of stl::vector is inconsistent

Has anyone encountered a strange issue like the one I'm experiencing? I'm working on a graph processing algorithm that uses a random seed for each run. unsigned int sseed = time(0); srand(sseed); Most of the time, my code runs smoothly without ...

How can arrays be merged while preserving their original order?

I have an array which contains arrays ordered by date like this: Array ( [1379167200] => Array ( [110] => Introduction to Banking | Saturday, September 14, 2013 - 10:00am ) [1380376800] => Array ( ...

What could be causing the "Failed prop type" error when dealing with nested cloned children, despite the parent having the correct initial values

Here is a question with two parts: What causes prop types checks to fail in a react-only scenario? How does a material-ui HoC interfere with type checking? When creating UI components, I keep the children unaware of each other by passing props through R ...

Expression enclosed in double quotes within a JavaScript string

Our company has encountered an issue with an FTL that involves a link with JavaScript functionality. The problem arises when the value contains an apostrophe, causing the link to break. To address this, we utilized the js_string method to solve the issue. ...