Hello 👋
In this post, I will show you how to make Lorem Ipsum generator in JS.
This is Part 3 of the 10 JS Project Challenge.
So let's get into it.
First, here is the video tutorial:
So let's start coding.
First, we need to create three files:
index.html
style.css
home.js
Once we have those files created, we can start coding.
Here is the code for index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Lorem Ipsum</title>
<!-- styles -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<section>
<div class="center">
<h3>Lorem Ipsum Generator</h3>
<form class="lorem-form">
<label for="amount">Paragraphs:</label>
<input type="number" name="amount" id="amount" placeholder="5" />
<button type="submit" class="btn">generate</button>
</form>
</div>
<article class="lorem-text"></article>
</section>
<!-- javascript -->
<script src="app.js"></script>
</body>
</html>
We are just creating a Simple form with Number input and with a button. Then we have a section, where it will be our generated text.
Now, let's move to the styling!
Open style.css and write in that code.
@import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap');
*{
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: 'Roboto', sans-serif;
}
.center{
display: inline-block;
margin-top: 100px;
margin-left: 42.5vw;
}
h3{
font-size: 1.5rem;
font-weight: bold;
}
article{
margin: 50px 25px 0 25px;
}
button{
background-color: skyblue;
border: none;
border-radius: 5px;
padding: 10px;
margin-left: 15px;
font-size: 1rem;
font-weight: bold;
cursor: pointer;
transition: 0.3s;
}
button:hover{
background-color: #00bfff;
}
I think the CSS has no explanation here, so let's move to the JavaScript.
In app.js paste this code.
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.`,
];
const form = document.querySelector(".lorem-form");
const amount = document.getElementById('amount');
const result = document.querySelector('.lorem-text');
form.addEventListener('submit', (e) => {
e.preventDefault();
const value = parseInt( amount.value);
const random = Math.floor(Math.random() * text.length);
if(isNaN(value) || value < 1 || value > 9) {
result.innerHTML = `<p class ="result align="center">${text[random]}</p><br>`;
}
else{
let tempText = text.slice(0, value);
tempText = tempText.map(function(item){
return `<p class ="result" align ="center">${item}</p><br>`;
}).join("")
result.innerHTML = tempText;
}
});
So, at first we have a text array with Lorem Ipsum Text, so we can grab that text and use it.
Then we need to declare variables for form, input and result.
Then we are listening to user to click button, and when they clicked it, we are changing the value from original string, to Integer through parseInt( amount.value).
If the value is Nan(user have-not write anything to the input field), or is less than 1 and bigger than 9, we want to randomly generate text through Math.random() - variable random which we declared.
If the user wrote the correct value, we want to pick text from the array, that is corresponding to the correct value. Then we want to map(pick a corresponding text from array) and return and HTML element with this text.
And then we want to just print the text using innerHTML.
And that is. Now you can generate Lorem Ipsum whenever you need it.
Thanks for reading my post. I hope you learned something new!
Top comments (0)