I have made various attempts, but can someone please point out the issue with this array?

I've been working on creating a random quote generator that generates a new quote whenever a button is clicked. However, I seem to have everything set up correctly but for some reason, when the button is clicked nothing happens.

Below is the code I have implemented:

HTML code

<div class="quote-box">
   <p id = "quote-generator"> This is where the generated quote will be displayed </p>
   <button class="btn" onclick="function newQuote()"> Next </button>
</div>

JS code

var list =  [
'/"Your mind will always believe what you tell it. Feed it faith. Feed it the truth. Feed it with love. /"',
'/"A problem is a chance for you to do your best./"',
'/"Learn how to be happy with what you have while you pursue all that you want./"',];`

const randomNumber = Math.floor(Math.random()*list.lenght);

function newQuote() {

document.getElementById("quotes-generator").innerHTML = list [randomNumber];`
}

Answer №1

Common Mistakes in Coding

  • A common mistake is using
    onclick="function newQuote()"
    instead of onclick="newQuote()" for function calls when clicking.
  • Another error to watch out for is mistyping the length property when generating random numbers from a list. The correct way is
    const randomNumber = Math.floor(Math.random() * list.length);
    , not
    const randomNumber = Math.floor(Math.random() * list.lenght);
  • Ensuring consistency between the ID specified in the HTML (quote-generator) and the one used in the script (quotes-generator) is crucial for proper functionality.
  • To refresh the random number each time the button is clicked, consider moving the random number generation logic inside the function rather than outside. This ensures that a new value is generated with each click.

var list = [
    '"Your mind will always believe what you tell it. Feed it faith. Feed it the truth. Feed it with love."',
    '"A problem is a chance for you to do your best."',
    '"Learn how to be happy with what you have while you pursue all that you want."',
];

function newQuote() {
    const randomNumber = Math.floor(Math.random() * list.length);
    document.getElementById("quote-generator").innerHTML = list[randomNumber];
}
<div class="quote-box">
    <p id="quote-generator"> this is where the quote will go </p> <button class="btn" onclick="newQuote()">
        Next </button>

</div>

For a more concise solution, you can simplify your code like this:

const list = [
    '"Your mind will always believe what you tell it. Feed it faith. Feed it the truth. Feed it with love."',
    '"A problem is a chance for you to do your best."',
    '"Learn how to be happy with what you have while you pursue all that you want."',
];
newQuote = () => document.getElementById("quote-generator").innerHTML = list[Math.floor(Math.random() * list.length)];
<div class="quote-box">
    <p id="quote-generator">
        this is where the quote will go
    </p>
    <button class="btn" onclick="newQuote()"> Next</button>
</div>

Answer №2

  1. Don't forget to properly escape characters in array values, especially when using single quotes like '.
  2. Remove any extra commas at the end of arrays.
  3. Ensure you are calling functions correctly on button click events.

var list = ['"Your mind will always believe what you tell it. Feed it faith. Feed it the truth. Feed it with love."', '"A problem is a chance for you to do your best."', '"Learn how to be happy with what you have while you pursue all that you want."'];

function newQuote() {
  let rnd = Math.floor(Math.random() * list.length);
  let rqt = list[rnd];
  document.getElementById("quote-generator").innerHTML = rqt;
}
<div class="quote-box">
  <p id="quote-generator"> this is where the quote will go </p> <button class="btn" onclick="newQuote()"> Next </button>

</div>

Answer №3

let randomNum = Math.floor(Math.random()*list.size);

The correct spelling is `list.length` and not `list.lenght`.

Answer №4

To eliminate redundancy, consider randomizing the array once and then displaying it to the user in a rotating manner:

/* Shuffle the array using Durstenfeld shuffle algorithm */
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i],array[j]] = [array[j],array[i]];
}
}
const list = [
    '"Your mind will always believe what you tell it. Feed it faith. Feed it the truth. Feed it with love. "', 
    '"A problem is a chance for you to do your best."', 
    '"Learn how to be happy with what you have while you pursue all that you want."',
]; 
shuffleArray(list);
list.n=-1;
document.querySelector(".btn").onclick=newQuote;

function newQuote(){
  document.getElementById("quote-generator").innerHTML = list[++list.n%list.length];
}
newQuote();
<div class="quote-box">
  <p id="quote-generator"> this is where the quote will go </p> 
  <button class="btn"> Next </button>
</div>

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

"Exploring the art of extracting a string based on a specific pattern with JavaScript

Looking to format a phone number string by adding an extension? Consider alternatives to inserting at each index. For example, if the input is 1234567891346, the desired output would be (123) - 456 - 7891 Ext - 346. let phoneStr = '12345678912346&a ...

Is it possible to pass an Array into a callback function in element-ui's el-autocomplete component?

I attempted to utilize the el-autocomplete tag in its simplest form: using an Array returned by a callback function (JSFiddle version). Vue.component('button-counter', { data: function() { return { selectdusers: [], user: &ap ...

How Angular services transmit information to components

I have implemented a search field within my top-bar component and I am facing an issue in passing the input value of that search field to another component. Design Search service Top bar component Result component Operation Top bar component receives th ...

When clicking, expand the li element to 100% width and move the other siblings aside

I'm looking to arrange li elements in multiple columns with flexibility. https://i.sstatic.net/HJCZu.png <ul> <li class="yellow"> Yellow Block </li> <li class="red"> Red Block ...

designing a presentation with customizable durations for each slide

I am trying to implement a slideshow using the slides.js jquery plugin and I have a specific requirement for the duration of each slide. My goal is to have the first slide, which contains an embedded video, display for 7 seconds, while the subsequent slid ...

Ways to implement the useEffect hook within a table component for retrieving data from the backend

I'm in the process of creating a table that displays the following information: Id quantity of books 1 XX 2 ... 3 ... ... ... The quantity of books will be retrieved from the backend using useEffect useEff ...

I'm puzzled by the addition of attributes to the closing </span> tag in the HTMLElement.innerHTML. It seems unnecessary, and I

Currently, I am working with Angular 13 and utilizing a pipe to reformat text within a contenteditable div. The functionality is all in order until the point where the innerHtml gets replaced with the new code. It seems that the attributes from the last ch ...

What is the most effective method for dividing a string in C programming?

One of my acquaintances recently demonstrated a method of splitting and copying one string to another which caught my attention. char str[] = "05/09/2013"; char day[3]; char month[3]; char year[5]; memset(day, 0, sizeof(day)); memset(month, 0, sizeof(mon ...

Issue with Angular2 where stylesheets are not loading properly

In my various angular 2 components, I include my stylesheets in the following manner: @Component({ selector: 'rewards-component', styleUrls: [ '../../assets/styles/old-web-styles/old-web-styles.component.scss', ...

Combining multiple storageStates in a playwright context for efficient loading

I am trying to load multiple storageStates into a single context in playwright, but I am facing some issues. When using the following code: const context = await browser.newContext({ storageState: "telegram.json",storageState: "google. ...

Issue encountered while fetching data using jQuery AJAX request through PHP proxy

Currently, I am in the process of interviewing for a company and they have assigned me a take-home project with no time limit to finish. One specific requirement is to utilize a PHP API proxy to bypass CORS restrictions for their API. I am only allowed to ...

Opting for frontend technologies such as React or Angular to update a Silverlight application containing over 1000 unique forms and views

We are in the process of transitioning our Silverlight application to modern web technologies like React or Angular due to the impending end of life for Silverlight by the end of this year. We are seeking advice on selecting the most suitable frontend tec ...

Using Vue.js watchers can sometimes cause an endless loop

I'm working on a unique aspect ratio calculator. How can I ensure my code doesn't get stuck in an endless loop when dealing with 4 variables that are dependent on each other? To address this, I implemented 4 watchers, each monitoring a specific ...

Creating unique random mesh placement in Three.js without overlapping

Is there a way to prevent circles from overlapping when randomly placed on the scene at coordinates (x,y)? I have a series of circles with varying positions and would appreciate any solutions or ideas. ...

Clicking the identical button on multiple overlapping elements using Selenium and Node.js

Working with Selenium has presented a challenge when trying to close multiple HTML elements that share the same "close" button and overlap each other. The initial approach of looping through them individually to close seemed unsuccessful. The first step i ...

What is the best way to ensure that these social icons are perfectly centered on the page across all web browsers?

Visit my website here: foxweb.marist.edu/users/kf79g/contact.php I'm stuck on the final step needed to deploy my website and finish it. The issue I'm facing is with the social icons when viewed on medium and small screens. I want them to be cent ...

Integrate a resizable sidebar on the webpage's right side that dynamically adjusts the layout

As I develop a Chrome Extension, my goal is to incorporate a sidebar into all webpages without overlapping the existing content. The sidebar should be placed beside the content, effectively reducing the width of the body of the webpage to the initial width ...

A dynamic star rating plugin in jQuery that allows for partial star ratings

Can you offer some guidance? I've searched on google but couldn't find anything helpful. I'm looking for a star rating system for my website that can display an initial value with decimals (like 2.75 displaying as 3/4 of a star) while only a ...

The positioning of Div elements constantly shifts unpredictably

Looking to create a tournament table using HTML and Bootstrap grid elements. Progress so far: I wish I could share an image of the current layout, but my reputation is too low. Here's a link instead: https://i.sstatic.net/OedPj.jpg Encountering two ...

What is the best way to display two items side by side from a list of items in HTML?

I have a list of items that are displayed in `webView` with 4 elements per row. However, for `mobileView`, I would like to show only 2 elements in each row. Below is an example from my HTML file: <div class="row my-3 cust-heading" style="margin-left: 3 ...