Html random text script

Создаем собственный lorem ipsum генератор на JavaScript

Генерация контента из различных случайных слов может быть очень полезна для каких-либо тестов. Вот почему сегодня мы создадим функцию, которая будет это делать.

Безусловно, можно использовать какую-нибудь библиотеку, но, так как создание такой генерации не слишком сложно и не займет много строк кода, было бы неплохо написать ее самому.

Для генерации контента нам понадобятся три функции и источник самих слов:

  1. Функция, возвращающая случайное число.
  2. Функция, которая предоставляет нам случайное слово.
  3. Функция, которая делает из слов полноценную строку.
  4. Источник слов в виде массива строк (можно взять из моего Github Gist).

1. Генерация случайного числа

Так как мы хотим получить случайное слово из нашего массива, нам надо генерировать случайный индекс. С учетом этого, следует помнить о минимальном и максимальном значении индекса массива.

Math.random(); // Returns 0.534098468876492

С помощью функции Math.random() мы получаем дробное число от 0 до 1 (не включая 1). Когда мы умножаем его, например, на 10, то получаем число от 0 до 10 (также не включая верхнюю границу). Но в нашем случае, нам хочется получить число от 0 до 10, включая верхнюю границу.

Math.random() * (10 - 0) + 0; // Returns 8.448742196214798

Но сейчас мы все еще получаем дробное число. Мы должны использовать Math.round , чтобы сделать его целым.

Math.round(Math.random() * (10 - 0) + 0) // Returns 6 or 5 or 9 or 10

Благодаря этим вычислениям мы получаем целое число от 0 до 10, включая обе границы. Вы также можете протестировать этот код.

let number = 0; let steps = 0; while(number != 10)

Здесь вы запускаете цикл до того момента, пока число не станет равным 10. Отслеживая количество итераций, вы можете сказать, сколько их понадобилось. Если вы запустите этот код несколько раз, то поймете, что каждый раз количество проходов по циклу будет разным.

function randomNumber(min, max)

Это финальная функция получения случайного числа в диапазоне. Давайте продолжим и сделаем функцию получения случайного слова из массива.

2. Получение случайного слова

Я нашел хорошую коллекцию слов, которую можно использовать. Вы также можете найти ее на Github Gist. В этой статье я буду использовать лишь часть.

const word = [ "Got", "ability", "shop", "recall", "fruit", "easy", "dirty", "giant", "shaking", "ground", "weather", "lesson", "almost", "square", "forward", "bend", "cold", "broken", "distant", "adjective." ]

Будем использовать randomNumber функцию, которую мы сделали на предыдущем шаге. Для получения случайного числа нам необходимо задать диапазон следующим образом.

const word = words[randomNumber(0, words.length - 1)];

Нижняя граница это 0, потому что индексы в массивах начинаются с 0. Верхняя граница легко вычисляется как words.length — 1 . Мы задаем ее таким образом, потому что в нашем случае в массиве хранятся 20 слов, поэтому words.length вернет 20. Но по ранее упомянутой причине (индексы в массиве начинаются с 0), чтобы получить индекс последнего элемента, необходимо отнять 1.

Итак, мы имеет вторую функцию, которая возвращает случайное слово.

3. Получение строки со случайными словами

Сейчас мы хотим получить несколько слов и сделать из них строку. Лучшим решением будет создать массив из 10 элементов.

[. Array(10)] // Returns [undefined, undefined, . ] with 10 items

Используя .map метод, мы можем пройтись по массиву и для каждого элемента сгенерировать случайное слово.

[. Array(10)].map(() => getRandomWord()) // Returns ["hand", "close", "ship", "possibly", "metal", "myself", "everybody", "serious", "adult", "favorite"]

В данный момент у нас есть просто массив случайных слов, но чтобы сделать его строкой, мы должны разделить элементы пробелом. Это можно сделать методом .join(») .

[. Array(10)].map(() => getRandomWord()).join('')

Также мы хотим добавить читабельности нашей строке, а именно сделать первое слово с заглавной буквы. Давайте обновим функцию getRandomWord .

function getRandomWord(firstLetterToUppercase = false)

Теперь создадим функцию generateWords . Теперь в getRandomWord(i === 0) будем передавать сравнение индекса с 0, чтобы сделать первое слово (чей индекс как раз равен 0) заглавным.

function generateWords(length = 10) < return [. Array(length)].map((_, i) =>getRandomWord(i === 0)).join(' ').trim() + '.'; >

4. Завершение

Мы написали все функции, так что можем посмотреть на весь код.

const word = [ "Got", "ability", "shop", "recall", "fruit", "easy", "dirty", "giant", "shaking", "ground", "weather", "lesson", "almost", "square", "forward", "bend", "cold", "broken", "distant", "adjective." ] function getRandomWord(firstLetterToUppercase = false) < const word = words[randomNumber(0, words.length - 1)]; return firstLetterToUppercase ? word.charAt(0).toUpperCase() + word.slice(1) : word; >function generateWords(length = 10) < return [. Array(length)].map((_, i) =>getRandomWord(i === 0)).join(' ').trim() + '.'; > function randomNumber(min, max)

Протестировать его можно на Runkit.

Источник

Html how to get random text in html

Solution 1: You just need to use an statement: Solution 2: Beside an statement, you could use a conditional operator Solution 1: First, you had typo in your last line of JavaScript — (ID is supposed to be Id) — I’ve changed, instead of using JQuery, I used pure JavaScript. http://jsfiddle.net/qVf8G/ This code is using the native JavaScript methods for finding the spam paragraph and then addressing the content of it as and assigning the random text to it.

Show Random Text in HTML Input on Reload

This should do it. You can simply add more sentences to the array holding the samples.

var texts = [ "I am a sentence.", "Some nice stuff.", "I am random too!" ];document.getElementById('randomText').value = texts[Math.floor(Math.random()*texts.length)];

On every reload it will show random number.

// find elements var banner = $("#banner-message-text") banner.val(parseInt(Math.random()*18546876546));
body < background: #20262E; padding: 20px; font-family: Helvetica; >#banner-message < background: #fff; border-radius: 4px; padding: 20px; font-size: 25px; text-align: center; transition: all 0.2s; margin: 0 auto; width: 300px; >button < background: #0084ff; border: none; border-radius: 5px; padding: 8px 14px; font-size: 15px; color: #fff; >#banner-message.alt < background: #0084ff; color: #fff; margin-top: 40px; width: 200px; >#banner-message.alt button
let messages = ["Hi", "Hey", "Hello", "Please make some attempts", "holla"]; // We can use inbuilt Math object to perform mathematical operations. // to get a random number between 0 and the total size of messages array, we can use it as follows. // Math.floor will return the largest integer which is less than or equal to that random number. let message = messages[Math.floor(Math.random()*messages.length)]; // to select your input element and set default value, you can do $('input').val(message); 

Generate custom number of lorem ipsum words in HTML, Just press the shortcut key ( alt+l on all platforms) to insert some lorem ipsum text. Type lorem(, ) in your

VS Code tips — Generate lorem ipsum in html files

Today’s VS Code tip: Emmet lorem Just type lorem in #html to generate a paragraph of dummy Duration: 1:47

How to Generate a RANDOM STRING in JavaScript and HTML

VS Code: How To Create Lorem Ipsum Text In An HTML File

One way to place lorem Ipsum dummy text with an html document is to use a heading tag such Duration: 3:06

Random text to be displayed in body of HTML

As you’ve worked to improve your question and you did have a working function for randomText . If you add a target to the HTML like

and then add document.getElementById(«spam»).innerHTML = randomtext(); it will display the output from your randomtext in the spam paragraph.

This code is using the native JavaScript methods for finding the spam paragraph document.getElementById(«spam») and then addressing the content of it as innerHTML and assigning the random text to it.

Transfer random String to .innerHTML, document.getElementById(«randomText»).innerHTML = this[‘text’ + randomNumber];.

HTML random number to text

You just need to use an if..else statement:

Beside an if statement, you could use a conditional operator

function RandomID() < var rnd = Math.floor(Math.random() * 11); document.getElementById('id').value = rnd; document.getElementById('out').innerHTML = rnd >= 1 && rnd

VS Code tips — Generate lorem ipsum in html files, Today’s VS Code tip: Emmet lorem Just type lorem in #html to generate a paragraph of dummy Duration: 1:47

Javascript Shuffle and Random Text in every second using two Function doesn’t work

First, you had typo in your last line of JavaScript — document.getElementByID(«fruit»).innerHTML; (ID is supposed to be Id) — document.getElementById(«fruit»).innerHTML;

I’ve changed, instead of using JQuery, I used pure JavaScript.

var fruit = ["Apple", "Banana", "Cerry", "Dragonfruit","Eldberry", "Guava", "Jackfruit", "Longan", "Mango", "Orange", "Pineapple", "Watermelon"]; var t = setInterval(function() < var randomNumber = Math.round( Math.random() * (fruit.length-1) ); const frt = document.getElementById('fruit'); //get element that you want to change frt.innerHTML = fruit[randomNumber];//set the value >, 1000); 

you are calling an ID using «dot» insted of «#» you need to change for animal $(‘.animal’) to $(‘#animal’) and $(‘.animal1’) to $(‘#animal’) same for fruit1.

      , 1000); document.getElementById("fruit").innerHTML; var animal = ["Ant", "Bear", "Cat", "Dogt","Elephant", "Gorilla", "Horse", "", "Jelly fish", "Lion", "Monkey", "Pinguin", "Rabit", "Sheep", "Turtle", "Unicorn", "Zebra"]; var t = setInterval(function() < var randomNumber = Math.round(Math.random()*(animal.length-1)); $('#animal').html(animal[randomNumber]); >, 1000); document.getElementById("animal").innerHTML; var fruit = ["Apple", "Banana", "Cerry", "Dragonfruit","Eldberry", "Guava", "Jackfruit", "Longan", "Mango", "Orange", "Pineapple", "Watermelon"]; var t = setInterval(function() < var randomNumber = Math.round(Math.random()*(fruit.length-1)); $('#fruit1').html(fruit[randomNumber]); >, 1000); document.getElementById("fruit1").innerHTML; var animal = ["Ant", "Bear", "Cat", "Dogt","Elephant", "Gorilla", "Horse", "", "Jelly fish", "Lion", "Monkey", "Pinguin", "Rabit", "Sheep", "Turtle", "Unicorn", "Zebra"]; var t = setInterval(function() < var randomNumber = Math.round(Math.random()*(animal.length-1)); $('#animal1').html(animal[randomNumber]); >, 1000); document.getElementById("animal1").innerHTML;  

Show Random Text in HTML Input on Reload, I would like to show a random string of text in an html field on page load/reload. I would like it to pick a random string of text from a list

Источник

Random text display using JavaScript – 1

This little JavaScript tip involves randomly displaying a text string from a list. And this is how we shall be going about it:

  • Create a new array and store the list of text strings in it
  • Use the JavaScript Math.random() method to obtain a random number
  • Convert the random number into an integer because the random() method throws a floating point (decimal) number between 0.0 and 1.0
  • Get the array element corresponding to the randomly generated integer.
  • Display the text string using document.write() or the JavaScript alert() .

Creating the array that stores the text strings

var r_text = new Array (); r_text[0] = "All the leaves are brown"; r_text[1] = "And the sky is grey"; r_text[2] = "I've been for a walk"; r_text[3] = "On a winter's day"; r_text[4] = "I'd be safe and warm"; r_text[5] = "If I was in L.A."; r_text[6] = "California dreaming, On such a winter's day";

Remember, JavaScript arrays are zero indexed (the first element of an array in JavaScript has an index of 0). Our array r_text consists of seven elements. We, thus, need an integer between 0 and 6.

Generating a random number

The variable i now contains a floating point (decimal) number between 0 and 1. We have to convert it to an integer between 0 to 6 so that it can be used as an index to retrieve the string from the r_text array.

We multiply the random floating point number (whose value is between 0.0 and 1.0) by 7 so that we get a number (again a floating point) that ranges from 0.0 to 7.0. The Math.floor() is used to round down this number. Thus, 0.345… would result in 0 and 6.893.. would be floored to 6.

The above three JavaScript statements can actually be combined into one:

var i = Math.floor(7*Math.random())

Displaying the text

The final step is to display the text through document.write() method.

We now place all this code between tags.

You can also pack all this code in an external JavaScript file that is called from your web page. I would suggest that, unless its absolutely necessary, you should segregate all JavaScript code into an external file. This way you need to maintain only one file.

When can you use this nice tip?

In the past, I have displayed a random quote or a randomly selected a testimonial on the web page. And this is how I go about it.
Most of my JavaScript code is placed in an external file (.js) that is called from desired web pages. I put all the testimonials or quotes that I want to display, in an array and then use the code above to have one displayed on the web page. And I can change this array to have a new set of testimonials or quotes, (which involves modifying only one file) and all web page are changed without additional effort.

Источник

Читайте также:  Java reflection private final field
Оцените статью