Randomly choosing text with Javascript and displaying it - javascript

I'm having one of those days where I can't put into words what I'm trying to find. So, forgive me if this question has been asked before, if it has, I simply cannot find it.
If I have ten different lots of text, how can I randomly select one of them with Javascript, and display it.
The closest I've got is this:
var textArray = [
'Hello Fred',
'Hello Jimmy',
'Hello Terry'
];
var randomNumber = Math.floor(Math.random() * textArray.length);
audioElement.setAttribute('src', textArray[randomNumber]);
<p id="text-here">This is where I want the text to go</p>
I'm pretty sure this isn't close to what I need though.

I've tested it and it works just fine. Just enclose your array string values in double quotes and everything will work as you expected.
Here it is just setting the innerHTML value of p tag which is selected by id randomNumber and then set it with random text value of your array.
getElementById: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
innerHTML: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
var textArray = [
"Hello I'm Fred1",
"Hello I'm Jimmy1",
"Hello I'm Terry1",
"Hello I'm Fred2",
"Hello I'm Jimmy2",
"Hello I'm Terry2",
"Hello I'm Fred3",
"Hello I'm Jimmy3",
"Hello I'm Terry3"
];
var randomNumber = Math.floor(Math.random() * textArray.length);
document.getElementById("randomNumber").innerHTML = textArray[randomNumber];
<p id="randomNumber"> </p>

Create a function to create random number
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
Call the function to get a random number which will act as the array index
var index = getRandomInt(9)
Now considering you have array as 'textArray' then you can write
var text = textArray[index]
Now to update the value in paragraph
document.getElementById("text-here").innerHTML=text;

Related

Generate random using button using JavaScript

How can I get a button to generate a random emoji (from a list of emojis) every time it is clicked using JavaScript.
You need to store your emojis as their hex values, not as their HTML entity encoded form. Also, it seems the Unicode values you picked map to Japanese characters, not emojis. Here's a working (except for actually using Japanese characters) script that I cleaned up a bit:
var emojis = [0x128512, 0x128516, 0x128513, 0x128514];
var display = document.getElementById('emojiDisplay');
function displayEmoji(){
var random = Math.floor(Math.random() * emojis.length);
var emoji = emojis[random];
display.innerHTML=`<h2>${String.fromCharCode(emoji)}</h2>`;
}
You are replacing the emoji list in the funcition
var emojiList = ['&#128512', '&#128516', '&#128513', '&#128514'];
var display = document.getElementById('emojiDisplay');
function displayEmoji() {
let randomEmojiIndex = Math.floor(Math.random() * emojiList.length);
emoji = emojiList[randomEmojiIndex];
display.innerHTML = `<h2>${emoji}</h2>`;
}

javascript, getting a random number result in each singular array

I'm not sure how to word the question and i'm still quite new at javascript.
So I've got a random quote generator that has each quote result as an array. I'd like to add in two items in the array which I've got so far but having one result be a random number generated eg "2 quote" but having 2 be randomised each time. The end result is for a browser based text game. So it could be "2 zombies attack" or "7 zombies attack." The code I have so far is:
var quotes = [
[x, 'Zombies attack!'],
[x, 'other creatures attack'],
['next line'],
]
function newQuote() {
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}
Ideally need x(or i however it's going to work) to be the result of a random number between a set range, each differently each array.
Thank you
p.s I forgot to mention that not all the quotes require a number. Thats why I've done it as a double array.
If I understand your goal correctly, you want to have a set of similar-ish message templates, pick one of them at some point and fill it with data, correct? There's a lot of ways to tackle this problem, depending on how varying can your templates be. For a simple case in my head where you just need to prepend a number to a string I'd do something like this:
var messages = [" zombies attack",
" other creatures attack"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = numberOfMonsters + messages[messageIndex]; // construct a resulting message
document.getElementById('quote').textContent = result;
If you'd rather have more complex strings where you don't necessarily add a number (or any string) to the beginning, like ["There's X things in the distance", "X things are somewhere close"], then I'd recommend to either come up with some sort of string formatting of your own or use a library to do that for you. sprintf.js seems to be just right for that, it will let you do things like this:
var messages = ["%d zombies attack",
"A boss with %d minions attacks"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = sprintf(messages[messageIndex], numberOfMonsters) // format a final message
document.getElementById('quote').textContent = result;
EDIT: Your task is much more complex than what is described in the original question. You need to think about you code and data organization. You have to outline what is finite and can be enumerated (types of actions are finite: you can loot, fight, move, etc.), and what is arbitrary and dynamic (list of monsters and loot table are arbitrary, you have no idea what type and amount of monsters game designers will come up with). After you've defined your structure you can come up with some quick and dirty message composer, which takes arbitrary entities and puts them into finite amount of contexts, or something. Again, I'm sort of shooting in the dark here, but here's an updated version of the code on plunkr.
I solved it to do what I want and still have the numbers different. The issue was I should have had the number generator within the quote function. Also can create multiple variables to use too for different number generators. The plan is to then integrate it with php to add content dynamically. Which I can do. Thanks Dmitry for guiding me in the right direction.
function newQuote() {
var MonsterOne = Math.floor((Math.random() * 14) + 0);
var MonsterTwo = Math.floor((Math.random() * 14) + 0);
var MonsterThree = Math.floor((Math.random() * 14) + 0);
var MonsterFour = Math.floor((Math.random() * 14) + 0);
var quotes = [
['Test', MonsterOne, 'One'],
['Test', MonsterOne,'Two'],
['Test', MonsterThree, 'Three'],
[MonsterFour, 'Four'],
['Five'],
]
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}

Javascript utilizing array won't work

I am trying to achieve an effect where one of the 6 text options appear randomly on load/refresh.
<html>
<body>
<script>
var myQuotes = new Array();
myQuotes[0] = "text option 1";
myQuotes[1] = "text option 2";
myQuotes[2] = "text option 3";
myQuotes[3] = "text option 4";
myQuotes[4] = "text option 5";
myQuotes[5] = "text option 6";
var myRandom = Math.floor(Math.random()*myQuotes.length);
$('#myQuote').html(myQuote[myRandom]);
</script>
</body>
</html>
I tried borrowing code from here: https://forum.jquery.com/topic/how-can-i-show-a-different-quote-at-random-on-page-refresh
$('#myQuote').html(myQuote[myRandom]);
change to
$('#myQuote').html(myQuotes[myRandom]);
The script should put at the end of body for the ready of myQuote. And I suggest you to use the debug module of your browser. You will find things went wrong when the code execute at the last line.
There are two potential problems.
First, your myRandom variable may exceed the maximum index (5) of your myQuotes array. The length of myQuotes == 6; therefore, your formula below will return a value between 0 and 6 which will lead to an out of bounds error.
var myRandom = Math.floor(Math.random() * myQuotes.length);
Instead, use myQuotes.length - 1 like so (of course this assumes that your array is greater than zero, so do some length checking):
var myRandom = Math.floor(Math.random() * (myQuotes.length - 1));
Second, as pointed out by others, you are referring to a myQuote variable instead of myQuotes.
// You have:
$('#myQuote').html(myQuote[myRandom]);
// How about:
$('#myQuote').html(myQuotes[myRandom]);

Swapping original string halves

Can I write a function that reads the content of an HTML textbox with id "message" and then writes into the HTML element with id "shuffled" with the value of original string with it's two halves swapped?
Examples:
"it" -> "ti"
"electric" -> "tricele"
"this laptop is lame" -> "op is lamethis lapt"
Yap it is possible, check this out:
var swap = function(str){
var half = Math.floor(str.length / 2);
return str.substr(half, str.length) + str.substr(0, half);
};
swap("electric"); // tricelec
Have fun :)

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?).
When the user presses the Generate button, it would then output 3 random paragraphs from the list.
I've looked around on here, but can't really find anything that helps.
Thanks
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 paragraphArray
var randomInt = Math.floor(Math.random()*paragraphArray.length);
//ensure random integer isn't the same as last
if(randomInt == _oldInt)
pickRandom(paragraphArray);
else{
_oldInt = randomInt;
return paragraphArray[randomInt];
}
}
You can use Math.random to generate a random index from your list:
var paragraphs = [...]; # This is your list of paragraphs
function get_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.
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.

Categories