Random Paragraph Generator Using JavaScript

A Random Paragraph Generator is a tool that generates random text, usually consisting of a few sentences or a short paragraph. These generators can be used for a variety of purposes, such as generating filler text for web pages or testing the layout of a document.

In this blog, we will be discussing how to create a Random Paragraph Generator using JavaScript, one of the most popular programming languages used for web development. We will also be exploring the different applications of this tool and how it can be customized to suit your needs. So, let’s dive in and explore the world of Random Paragraph Generators using JavaScript!

Recently I shared a complete blog post on how to build a random password generator using JavaScript with source code please check this article first.

Steps to create a random paragraph generator using JavaScript:

Step 1: Set up the HTML structure

The first step is to create the basic HTML structure for your generator. This includes creating a text area where the generated paragraph will be displayed and a button to trigger the generation process.

Step 2: Create the JavaScript function

Next, you need to create a JavaScript function that generates a random paragraph. To do this, you can create an array of sentences and use the Math.random() method to randomly select sentences from the array.

Step 3: Display the generated paragraph

After generating the paragraph, you need to display it in the text area you created earlier. This can be done using JavaScript by setting the value of the text area to the generated paragraph.

Step 4: Add event listener to the button

Finally, you need to add an event listener to the button you created in step 1. This event listener should trigger the JavaScript function you created in step 2 when the button is clicked.

Video Tutorial Random Paragraph Generator Using JavaScript

This video is created by the Wscube Tech YouTube channel please subscribe to this channel for more videos like this one.

I hope you liked the demo of the Random Paragraph generator and watch the video tutorial till the end. If you didn’t watch the video, I suggest you watch it till the end because, in the video, I’ve tried to explain each line of code by written comments and shown which line of code does what.

You Might Like This

Random Paragraph Generator [Source Codes]

To create a Random Paragraph Generator using HTML CSS & JavaScript, follow the given steps line by line:

  1. Create a folder. You can put any name of this folder and create the below-mentioned files inside this folder.
  2. Create a index.html file. File name must be index and its extension .html
  3. Create a style.css file. File name must be style and its extension .css
  4. Create a script.js file. File name must be script and its extension .js

Once you create these files, paste the given codes into the specified files. If you don’t want to do these then scroll down and download the source codes of this Password Generator by clicking on the given download button. It’s free of cost.

First, paste the following codes into your index.html file.

HTML FILE

<!DOCTYPE html>
<!-- Created by Coding Pakistan.com -->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="main">
        <div class="row">
            <div>
                Paragraphs:
            </div>
            <div>
                <input type="number" value="5" id="items">
            </div>
            <div>
                <button onclick="generate()">Generate</button>
            </div>
        </div>
        <div class="row" style="display: block;" id="data">
        </div>
    </div>
    <script src="app.js"></script>
</body>
</html>

Second, paste the following codes into your style.css file.

CSS FILE

/* Created by Coding Pakistan.com */
* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
}
#main {
    width: 100%;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: start;
    align-items: center;
    background-color: #f1f5f8;
}
.row {
    width: 1000px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    padding: 10px;
    font-size: 20px;
    margin-top: 15px;
}
.row div {
    padding: 10px;
}
.row input {
    width: 100px;
    padding: 5px;
    border-radius: 5px;
    border: 0;
    font-size: 20px;
    box-shadow: 0px 0px 2px grey;
}
.row button {
    background-color: #49a6e9;
    padding: 5px;
    border-radius: 5px;
    border: 0;
    font-size: 20px;
    border-radius: 5px;
    color: white;
    outline: none;
    border: none;
}
.row p {
    margin-top: 10px;
    font-size: 16px;
    text-align: justify;
}

Last, paste the following codes into your app.js file.

JavaScript FILE

// Created by Coding Pakistan.com
const text = [
    `Jelly sweet roll jelly beans biscuit pie macaroon chocolate donut. Carrot cake caramels pie sweet apple pie tiramisu carrot cake. Marzipan marshmallow croissant tootsie roll lollipop. Cupcake lemon drops bear claw gummies. Jelly bear claw gummi bears lollipop cotton candy gummi bears chocolate bar cake cookie. Cupcake muffin danish muffin cookie gummies. Jelly beans tiramisu pudding. Toffee soufflé chocolate cake pastry brownie. Oat cake halvah sweet roll cotton candy croissant lollipop. Macaroon tiramisu chocolate bar candy candy carrot cake jelly sweet. Gummies croissant macaroon dessert. Chocolate cake dragée pie.`,
    `Next level tbh everyday carry, blog copper mug forage kitsch roof party pickled hammock kale chips tofu. Etsy shoreditch 8-bit microdosing, XOXO viral butcher banh mi humblebrag listicle woke bicycle rights brunch before they sold out ramps. Twee shabby chic taiyaki flannel, enamel pin venmo vape four loko. Hexagon kale chips typewriter kitsch 8-bit organic plaid small batch keffiyeh ethical banh mi narwhal echo park cronut.`,
    `Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.`,
    `Cat gets stuck in tree firefighters try to get cat down firefighters get stuck in tree cat eats firefighters' slippers kitty power ignore the squirrels, you'll never catch them anyway for what a cat-ass-trophy! or purr as loud as possible, be the most annoying cat that you can, and, knock everything off the table. Pretend you want to go out but then don't bite off human's toes, yet disappear for four days and return home with an expensive injury; bite the vet so catch eat throw up catch eat throw up bad birds. `,
    `This opera's as lousy as it is brilliant! Your lyrics lack subtlety. You can't just have your characters announce how they feel. That makes me feel angry! Anyhoo, your net-suits will allow you to experience Fry's worm infested bowels as if you were actually wriggling through them.
    I just told you! You've killed me! Fry! Quit doing the right thing, you jerk! Michelle, I don't regret this, but I both rue and lament it. Morbo can't understand his teleprompter because he forgot how you say that letter that's shaped like a man wearing a hat.`,
    `Airedale hard cheese mozzarella. Pecorino melted cheese port-salut emmental babybel cheese and wine melted cheese manchego. Everyone loves blue castello everyone loves fromage cheese slices airedale cheddar cream cheese. Bavarian bergkase who moved my cheese halloumi port-salut gouda jarlsberg ricotta rubber cheese. Stinking bishop smelly cheese brie.`,
    `Salvia glossier subway tile, leggings mustache YOLO semiotics chia. Pitchfork tbh af blog church-key meggings vaporware PBR&B master cleanse post-ironic man bun pabst mustache letterpress synth. Snackwave raw denim godard, 3 wolf moon shaman offal kitsch unicorn live-edge selvage schlitz fashion axe vaporware drinking vinegar prism. Shabby chic tacos artisan, chambray chicharrones cardigan leggings typewriter af pop-up williamsburg meditation PBR&B viral. You probably haven't heard of them DIY jean shorts subway tile fashion axe bushwick kitsch tumeric cloud bread vaporware freegan franzen pork belly chicharrones banh mi.`,
    `Man braid celiac synth freegan readymade, pitchfork fam salvia waistcoat lomo bitters gentrify four loko. Pitchfork semiotics post-ironic vegan. Tofu meditation microdosing hashtag semiotics venmo. Flexitarian vape tilde taiyaki. Prism poutine farm-to-table, messenger bag vegan taxidermy tattooed sartorial squid jean shorts fixie selvage trust fund vape.`,
    `Rutters Plate Fleet boom chandler Brethren of the Coast handsomely lookout marooned brigantine knave. Buccaneer gangway jack rum loot spyglass line Jack Tar fore gaff. Gaff topmast scuttle ballast swab draught measured fer yer chains dance the hempen jig Chain Shot yardarm.`,
];
function shuffle(array) {
    let currentIndex = array.length,
        randomIndex;
    // While there remain elements to shuffle.
    while (currentIndex != 0) {
        // Pick a remaining element.
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex--;
        // And swap it with the current element.
        [array[currentIndex], array[randomIndex]] = [
            array[randomIndex], array[currentIndex]
        ];
    }
    return array;
}
const item = document.querySelector("#items")
const dataContainer = document.querySelector("#data")
const generate = () => {
    if (isNaN(item.value) || item.value < 0 || item.value > 9) {
        const randomIndex = Math.floor(Math.random() * text.length)
        dataContainer.innerHTML = `<p> ${text[randomIndex]} </p>`
    } else {
        const localText = shuffle(text);
        const data = localText.slice(0, item.value)
        const parars = data.map(
            (d) => {
                return `<p> ${d} </p>`
            }
        )
        console.log(parars)
        console.log(parars.join(""))
        dataContainer.innerHTML = parars.join("");
        // array to string
    }
}

Paragraph Generator [Download Source Codes]

That’s all, now you’ve successfully created a Random Paragraph Generator in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any problems, please download the source code files from the given download button. It’s free and a zip file will be downloaded that contains the project folder with source code files.

random paragraph generator using javascript

 

Leave a Comment