Skip to content Skip to sidebar Skip to footer

Select Random Paragraph From List

I am currently learning Javascript, and I'd like to create my own Lorem Ipsum generator. Basically, I would have a list of the paragraphs (in javascript, or in the HTML document?).

Solution 1:

You could simply have a Javascript Array and pick a random index and inject that paragraph into the DOM element. I've also updated the code to not repeat the previous random integer per your comment below.

Example (code untested)

//global to store previous random int
_oldInt = null;

var paragraphArray = ["Lorem ipsum delor...", "The great white...", "Chitty-chitty-bang-bang..."];  

//update element content (e.g. `<div>` with paragraph)document.getElementById("MyID").innerHTML = pickRandom(paragraphArray);

var pickRandom = function(paragraphArray){
    //random index of paragraphArrayvar randomInt = Math.floor(Math.random()*paragraphArray.length);
    //ensure random integer isn't the same as lastif(randomInt == _oldInt)
        pickRandom(paragraphArray);
    else{
        _oldInt = randomInt;
        return paragraphArray[randomInt];
    }
}

Solution 2:

You can use Math.random to generate a random index from your list:

var paragraphs = [...]; # This is your list of paragraphsfunctionget_random_paragraph() {
    var index = Math.floor(paragraphs.length * Math.random());
    return paragraphs[index];
};

The expression Math.floor(MAX_VALUE * Math.random()) generates a random integer x, where 0 <= x < MAX_VALUE.

Solution 3:

You need some paragraphs (here, a JavaScript array), a result box (here, a <div>) and a button (here, a... <button>).

When you click on the button, you want to add a paragraphs into the result.

var paragraphs = ['Lorem', 'ipsum', 'dolor', 'sit', 'amet'],
    nbParagraphs = paragraphs.length
    paragraph = null,
    result = document.getElementById('result'),
    button = document.getElementsByTagName('button')[0];

button.addEventListener('click', function() {
    /*
     * Math.random() return a number between 0 and 1
     * parseInt() return an integer (the 10 is here to say that we are in decimal)
     * parseInt(Math.random() * nbParagraphs, 10) return a number between 0 and the number of paragraphs, so we can use it to select a paragraph in the paragraphs array
     */
    paragraph = paragraphs[parseInt(Math.floor(Math.random() * nbParagraphs, 10))]
    result.innerHTML += '<p>' + paragraph + '</p>'
})

Here is a demo.

Post a Comment for "Select Random Paragraph From List"