In this lesson we will develop a random quotes generator.

We will make sure that clicking on a button, from time to time, generates a new sentence.

Try the example below by clicking on the button:

Random Quotes Generator

Development of the random quotes generator

First let’s develop the simple HTML code needed to create the generator.

We insert a container to contain everything where inside we first insert a title, after a div where we will insert the randomly generated sentence and finally a button to generate the event on click.

Here is the HTML code:

Banner Pubblicitario




Insert some CSS code to give some graphics to the project.

We then develop the JavaScript code.

First of all, let’s prepare the array that will contain all the phrases by choosing some quotes from famous people.

Then through the addEventListener event we call the function to generate a random element of the array upon clicking on the button.

We can simply use a function that generates a random number between 0 and the length of the array minus 1. Then we locate the sentence in the array using this number as an index.

Here is the complete code:



myQuotes = [
    'A volte sono le persone che nessuno immagina che possano fare certe cose quelle che fanno cose che nessuno può immaginare.',
    'La fantasia è più importante del sapere, perché il sapere è limitato.',
    'Chi dice che è impossibile non dovrebbe disturbare chi ce la sta facendo.',
    'C'è una forza motrice più forte del vapore, dell’elettricità e dell’energia atomica: la volontà.',
    'La misura dell’intelligenza è data dalla capacità di cambiare quando è necessario.',
    'La logica ti porta da A a B, l’immaginazione ti porta ovunque.',
    'Gli occhi sono lo specchio dell’anima… cela i tuoi se non vuoi che ne scopra i segreti.',
    'Imparerai a tue spese che nel lungo tragitto della vita incontrerai tante maschere e pochi volti.',
    'Ma guardi signora è facilissimo, le insegno io ad esser pazza. Basta gridare la verità in faccia a tutti, loro non ci crederanno e ti prenderanno per pazza.'
];

const buttonQuote = document.getElementById('new-quote');

buttonQuote.addEventListener('click',generate);

function generate(){
    randomQuote = randomNumber(myQuotes);

    const quote =  document.getElementById('quote');
    quote.innerHTML = myQuotes[randomQuote];
}

function randomNumber(array) {
    const num = Math.round(Math.random() * (array.length - 1));
    return num;
}

Conclusions

In this lesson we have developed a simple random quotes generator, choosing some famous quotes including Pirandello, Turing and Albert Einstein.

Banner pubblicitario

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript