For the website that I am creating, I am looking to have a random welcome message be generated using a JavaScript array and be displayed on the screen using the innerHTML property. So far, I've created the array with the messages, but I'm stuck on how to select a random one, then insert it using the innerHTML property. Any help would be awesome.
For example
document.getElementById("your-elements-id").innerHTML = "<p>" + yourArray[Math.floor(Math.random() * yourArray.length)] + "</p>";
Put it inside your window.onload or something.
Try this https://jsfiddle.net/ywnv00xc/1/
const messages = ['message1', 'message2', 'message3', 'message4'];
const randomIndex = Math.round(Math.random()*messages.length);
document.getElementById("your-elements-id").innerHTML = messages[randomIndex];
From MDN:
const getRandomArbitrary = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
};
Related
I'm a student and have been attempting to create a program in JavaScript to create a function and generate a random integer (whole number) between 1 and 9. I have created two different programs for this in my testing but while using Visual Studio Code it doesn't print the generated number.
Please see code below and if you have any questions please let me know.
function random_num() {
let random_num = Math.floor(Math.random() * 9) +1;
return random_num;
}
console.log(random_num);
function random_num(min, max) {
min = Math.ceil(1);
max = Math.floor(9);
return Math.floor(Math.random() * (max - min)) + min;
}
console.log(random_num);
Thanks in advance!
Always save your result in variable then print it
function random_num(min, max) {
min = Math.ceil(1);
max = Math.floor(9);
return Math.floor(Math.random() * (max - min)) + min;
}
const randomNumber1 = random_num()
console.log(randomNumber1);
enter image description here
'use strict';
function random_num() {
let random_num = Math.floor(Math.random() * 9) +1;
return random_num;
}
const randomNumber = random_num()
console.log(randomNumber);
I found out that the first snippet will end up giving a number between 1 and 9 which is the exact thing you wanted but the problem is that you are not calling the function itself. So this should help.
console.log(random_num())
When you want to get the result of functions that return a value.
Here is the solution:
console.log(random_num());
Thanks for your suggestions, your answers have helped fix this for me! I'm just learning JavaScript so this help was greatly appreciated!
function random_num(min, max) {
min = Math.ceil(1);
max = Math.floor(9);
return Math.floor(Math.random() * (max - min)) + min;
}
const randomNumber1 = random_num()
console.log(randomNumber1);
As others have already pointed out, you need to be outputting your result somewhere, no? Online scripting environments have spoiled us a bit in recent years, but when you're doing thins locally, never assume your build assumes implicit return.
This is how an comand works
And this is my main.js
an little help please?i really need it and i would apreciatte much if you would help me
First of all you need to find the channel ID. Best to go into the Discord app and right click the channel and select "Copy ID". It should look something like this: 845346073543326453
Now to send something to that specific channel you have to do this:
const channel = client.channels.cache.get(845346073543326453);
channel.send("hello!")
For the random messages you just create an array and randomly pick one:
const random = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
}
let randomMsg = [`Howdy`, `Howdily doodily`, `Zoinks`]
channel.send(quotes[random(0, quotes.length - 1)])
To send it at a specific time there's many methods. I recommend using the cron package and reference this post: How can I send a message every day at a specific hour?
But if you just want a quick and really low effort way you could just use setInterval() and set the delay to an hour. So we end up with something like this:
const channel = client.channels.cache.get(845346073543326453);
const randomMsg = [`Howdy`, `Howdily doodily`, `Zoinks`]
const random = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
}
const sendRandomMsg = () => {
var d = new Date();
var n = d.getHours();
if (n === 12) {
channel.send(randomMsg[random(0, quotes.length - 1)])
}
}
setInterval(function(){ sendRandomMsg() }, 3600000);
You can add more functions into the if, in case you have more functions to run at specific times.
I'am trying to make a simple calculation generator in prompt window. But it should not generate a negative number as answer, such as: x-y=-answer
My code so far:
CodepenLink
How it should look like
function myFunction() {
var randomNumber = Math.floor(Math.random() * 10);
var nxtRandomNumber = Math.floor(Math.random() * 10);
var question = prompt("What is:"+ randomNumber+ " minus " + nxtRandomNumber);
if(nxtRandomNumber > randomNumber){
return ;
}
var result = Number(randomNumber) - Number(nxtRandomNumber);
document.getElementById("demo").innerHTML = "Number:" + answer + " was right!";
}
<p>Push the button to start </p>
<button onclick="myFunction()">Calculate!</button>
<p id="demo"></p>
make sure when you calculate nxtRandomNumber to use the value of randomNumber as a minimum.
So if randomNumber is 5, nextRandomNumber should be calculated to compute a number at least equal to 'randomNumber'
for ex:
nextRandomNumber = Math.floor(Math.random() * 10) + randomNumber;
Theres a trick to generate random number between 2 values.
var nxtRandomNumber = Math.floor(Math.random() * (10 - randomNumber) + randomNumber);
From mdn
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max.>>>
I have the following script, which is meant to generate 2 different numbers
<script type="text/javascript">
function GenerateRandomNumber2to6No1() {
var min = 2, max = 7;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return random;
}
var GenerateRandomNumber2to6No1 = GenerateRandomNumber2to6No1();
$('.GenerateRandomNumber2to6No1').html(GenerateRandomNumber2to6No1);
function GenerateRandomNumber2to6No2() {
var min = 2, max = 7;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return (random !== GenerateRandomNumber2to6No1) ? random: GenerateRandomNumber2to6No2();
}
var GenerateRandomNumber2to6No2 = GenerateRandomNumber2to6No2();
$('.GenerateRandomNumber2to6No2').html(GenerateRandomNumber2to6No2);
</script>
NUMBER 1: <span class = "GenerateRandomNumber2to6No1"></span>
NUMBER 2: <span class = "GenerateRandomNumber2to6No2"></span>
This usually works fine but occasionally the page will load and no numbers will appear. I'm guessing this is when GenerateRandomNumber2to6No2 happens to generate the same number as GenerateRandomNumber2to6No1. I thought that
return (random !== GenerateRandomNumber2to6No1) ? random: GenerateRandomNumber2to6No2(); accounted for this, but perhaps instead of generating another unique number when there's redundancy, it generates no number at all. Is this the case? If so, how can I fix this?
Thanks!
function getRand(){
var array=[2,3,4,5,6,7]
var newArray=[];
for(var i=0;i<2;i++){
var ran=~~(array.length*Math.random());
newArray[i]=array.splice(ran,1)[0]
}
return newArray
}
var ranArray=getRand();
var ran1=ranArray[0];
var ran2=ranArray[1];
console.log(ran1,ran2)
getRand() is a function to give you an array of distinct numbers.Since you only need two,it only loop two times,and give you an array,which you can make use of it.
Back to your code,from what I see,Gno2 should keep running until it got another number,I don't know why.It's the time you try to debug.
First I will try to change the max=2 to max=3,if the code may not work for some number,then you can quickly realize and found out the problem is in these two functions.
Then try to log,console.log(Gno1,Gno2),see what exactly the numbers are,also help you to know where is the problem.
I think this piece of code can help you
var rand1,rand2;
var min = 3;
var max = 6;
do {
rand1 = Math.floor(Math.random() * (max - min)) + min;
rand2 = Math.floor(Math.random() * (max - min)) + min;
}while(rand1 === rand2);
$('.GenerateRandomNumber2to6No1').html(rand1);
$('.GenerateRandomNumber2to6No2').html(rand2);
I'm trying to make a button that randomly sets a select option when clicked. I can't figure out what I am doing wrong though...
http://jsfiddle.net/GamerGorman20/nw8Ln6ha/25/
$('#rand').click(
function() {
randNum();
var num = "";
document.getElementById("mySelect").value.innerHTML = favWebComics[num];
});
var randNum = function() {
num = Math.round(Math.random() * 2) + 1;
return num;
};
The shown code is only a small part of the larger script housed in the linked jsfiddle.
I plan to add more selections later, but I want to get the code figured out before I spend time on those.
Worth mentioning, my understanding of this is very limited, so keeping the advice simple is GREATLY appreciated.
The relevant part of your code that you will need to change will look like this when complete (see the updated jsfiddle):
$('#rand').click(function() {
var $select = document.getElementById('mySelect'),
max = $select.getElementsByTagName('option').length - 1;
$select.selectedIndex = randNum(1, max);
myFunction();
});
var randNum = function(min, max) {
num = Math.floor(Math.random() * (max - min + 1)) + min;
return num;
};
var myFunction = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
document.getElementById("image").innerHTML = favWebComics[x][1];
document.getElementById("web").innerHTML = favWebComics[x][0];
document.getElementById("tags").innerHTML = "Tags: " + favWebComics[x][2];
};
I haven't changed the style or structure of your code, but just some of the basic properties.
The problem you have is with innerHTML. You cannot set innerHTML on an element's value.
Instead, what you can do is generate a random number and set the selectedIndex property of the select element to that random number.
Then, you'll call the function that displays the images and whatnot that you need.
You cannot change the select with innerHTML like this:
document.getElementById("mySelect").value.innerHTML = favWebComics[num];
You have to instead change the value, and apply the change like so
$("#mySelect").val("New text").change();
or
$("#mySelect").prop('selectedIndex', index).change();