How to Build Lorem Ipsum Text Generator Using JavaScript and Vite
In this article, let's learn how to build a flexible Lorem ipsum generator using Vite and JavaScript. From there, you will improve your programming skills over time.
Lorem ipsum is the text that programmers and designers around the world use as placeholders. If you interact with multiple UI prototypes, you may have used it before.
In this article, let's learn how to build a flexible Lorem ipsum generator using Vite and JavaScript . From there, you will improve your programming skills over time.
Why is Lorem Ipsum so popular?
The main reason is because it allows users or viewers to understand the visual appearance of the document or prototype without focusing too much on the placeholder.
Imagine you are designing a magazine. Instead of going through the trouble of copying text from different sources to make the design as realistic as possible, you can simply copy the standard lorem ipsum placeholder text and use that instead.
Lorem ipsum is so common that you don't even need to identify it as a text placeholder - almost anyone immediately recognizes it as an additional text.
Setting up the project and development server
You'll use the Vite build tool to set everything up. Make sure Node.js and Node Package Manager (NP) or Yarn are installed on your machine, then open a terminal and run:
npm create vite
Or:
yarn create vite
This creates an empty Vite project. Enter the project name, put the framework in vanilla and the variable 'vanilla'. Once that's done, navigate to the project directory with the cd command , then run:
npm I
Or:
Yarn
After installing all the dependencies, open the project in the editor of choice, then edit the project structure to look like this:
Now clarify the contents of the index.html file and replace it with:
Lorem Ipsum Generator
Lorem Ipsum Generator
25 3 Dùng thanh trượt đặt các tham số, sau đó nhấn nút "Generate". Bạn có thể sao chép text bằng cách nhấn nút "Copy to Clipboard"
This markup simply defines the user interface. The left side of the screen shows the controls, the right shows the output. Next, open the file main.js , delete its contents and add a line to enter style.css :
import './style.css'
Import Lorem files and define global variables
Open the project's GitHub repository, copy the contents of the lorem.js file and paste them into the local copy of lorem.js. Lorem.js outputs a long string of Lorem Ipsum text that other JavaScript files can use.
In the main.js file , import the lorem string from the lorem.js file and define the required variables.
import { lorem } from './lorem'; let text = lorem.replace(/[.,/#!$%^&*;:{}=-_`~()]/g, "").split(' '); let lastChar; let wordCountControl = document.querySelector("#w-count"); let paragraphCountControl = document.querySelector("#p-count"); let wordCountLabel = document.querySelector("#w-count-label"); let paragraphCountLabel = document.querySelector("#p-count-label"); let wordCount = wordCountControl.value; let paragraphCount = paragraphCountControl.value; let copy = document.querySelector(".copy");
This code uses a regular expression to remove any punctuation in the lorem text. The text variable associates the version of this edited lorem text. That makes it easier to create words and paragraphs.
Create generator functions
Any truly randomly generated sentence or paragraph needs punctuation. After defining the global variables, create a function named generateRandomPunctuation() , in that function create an array named characters & fill it in.
function generateRandomPunctuation() { let characters = [",", "!", ".", "?"]; let character = characters[Math.floor(Math.random() * characters.length)]; lastChar = character; return character; }
The above code block defines arrays, characters, containing different punctuation marks. It defines another variable, character, which it sets to a random element from the characters array . The global variable, lastChar, contains the same value that this function returns afterwards.
Next, create a function generateParagraph() with a count parameter that has a default value of 100.
function generateParagraph(count = 100) { }
In this function, declare a paragraph array and fetch the random word from the global text array, then push it to paragraph .
let paragraph = []; for (let i = 1; i <= count; i++) { paragraph.push(text[Math.floor(Math.random() * text.length)].toLowerCase()); }
Next, add code to capitalize the first letter of the first word of each paragraph:
let fl=paragraph[0]; paragraph[0] = fl.replace(fl[0], fl[0].toUpperCase());
Each paragraph ends with a punctuation mark (usually a period), so add code that adds a period at the end of each paragraph.
let lwPos = paragraph.length - 1; let lWord = paragraph[lwPos]; paragraph[lwPos] = lWord.replace(lWord, lWord + ".");
Next, implement the function to add a randomly generated punctuation to a random element in the paragraph array .
paragraph.forEach((word, index) => { if (index > 0 && index % 10 === 0) { let randomNum = Math.floor(Math.random() * 4); let pos = index + randomNum; let randWord = paragraph[pos]; paragraph[pos] = randWord.replace(randWord, randWord + generateRandomPunctuation()); let nWord=paragraph[pos + 1]; if (lastChar !== ",") { paragraph[pos + 1] = nWord.replace(nWord[0], nWord[0].toUpperCase()); } } })
This block of code generates a random punctuation character and appends it to the end of a random element from the paragraph array . After concatenating punctuation, it capitalizes the first letter of the next element if the punctuation is not a comma.
Finally, return the paragraph array formatted as a string:
return paragraph.join(" ");
Text lorem ipsum will have a structure based on the number of paragraphs the user selects. You can use an array to define this structure. For example, if the user wanted the text lorem ipsum to have 3 segments, the 'structure' array would look like this:
structure = ["First paragraph.", "n n", "Second paragraph.", "n n", "Third paragraph"]
In the above code block, each "n" represents the distance between each paragraph. If you log in structure.join("") in the browser console, you will see the following:
Create a function that automatically generates this structure and calls generateParagraph :
function generateStructure(wordCount, paragraph = 1) { let structure = []; for (let i = 0; i < paragraph * 2; i++) { if (i % 2 === 0) structure[i] = generateParagraph(wordCount); else if (i < (paragraph * 2) - 1) structure[i] = "n n"; } return structure.join(""); }
Add event listeners to controls
Add an 'input' event listener to the input element wordCountControl and in the callback function set wordCount to the input value. Then update this label.
wordCountControl.addEventListener("input", (e) => { wordCount = e.target.value; wordCountLabel.textContent= e.target.value; })
Next, add an 'input' event listener to the input element paragraphCountControl and in the callback function, set paragraphCount to the input value and update this label.
paragraphCountControl.addEventListener("input", (e) => { paragraphCount= e.target.value; paragraphCountLabel.textContent = e.target.value; })
Add a 'click' event listener to the copy button that calls copyText() when the event fires.
copy.addEventListener("click", ()=>copyText());
Finally, add the 'submit' event listener to the HTML form element and call the update UI function in the callback function.
document.querySelector("form").addEventListener('submit', (e) => { e.preventDefault(); updateUI(); })
Finalize and update UI
Create a function getControlValues that returns wordCount and paragraphCount as an object.
function getControlValues() { return { wordCount, paragraphCount }; }
Then create an updateUI() function that displays the generated text on the screen to the user:
function updateUI() { let output = generateStructure(getControlValues().wordCount, getControlValues().paragraphCount) document.querySelector(".output").innerText = output; }
Create a copyText() function that writes content to the clipboard whenever the user clicks the " Copy to Clipboard " button.
async function copyText() { let text = document.querySelector(".output").innerText; try { await navigator.clipboard.writeText(text); alert('Copied to clipboard'); } catch (err) { alert('Failed to copy: ', err); } }
Then call the updateUI() function :
updateUI();
Congratulations! You already have a lorem ipsum text generator using JavaScript and Vite.
You should read it
- Chrome Extensions for Developers
- How to create random text in Word
- Tutorial for creating slideshows in JavaScript with 3 easy steps
- JavaScript code to generate dynamic line graphs/charts
- JavaScript code to create box & whisker chart/graph templates with custom colors
- JavaScript code to create bubble chart with custom marker
- What is JavaScript?
- Syntax of JavaScript
- How to create a word counter in JavaScript
- How to make PIN Pad using HTML CSS & JavaScript
- JavaScript code to create Pareto charts & graphs
- Introduction to 2D Array - 2-dimensional array in JavaScript
Maybe you are interested
How to transfer photos from a laptop to a TV using DLNA 10 most beautiful flowers in the world 8 most expensive flowers on the planet, money is not sure to buy 11 most brilliant cherry blossoms in Japan Top 10 most beautiful cats in the world Winamp, the once-legendary music player will come back next year