So im trying to make a color guessing game
So i created a function that generates a color and returns it, which works fine
But since i have 3 buttons with #hex code on them 1 button has to be a correct answer and correct #hex has to be displayed in a color box
So im trying to put 3 #hex codes in each button and choose randomly which #hex code is the correct one and display it in HTML
i know the code is very bad but i still got a long way to go...
function randomColor(){
let randomColor = Math.floor(Math.random()*16777215).toString(16);
return randomColor
}
function arrayOfColors(){
let randColorArr = []
}
function generateColors(){
colorBox.style.backgroundColor = `#${correctColor}`
btn.forEach(button => button.innerHTML = `#${randomColor()}`)
}
generateColors()
randomColor - I made a correction to your function that will always return a valid color number,
arrayOfColors - I answered your question about the function and it now returns an array with three colors for your three buttons,
randomIntFromInterval - designed to generate numbers in a certain range that you determine,
generateColors -
I drew an array of three colors,
I drew a lottery for the position in the array that would be the correct color,
I gave the div the correct color, and the buttons all three colors including a click event that will check if the user won,
Immediately after clicking, a new game starts.
const colorBox = document.querySelector('div');
const btns = document.querySelectorAll('button');
function randomColor(){
let randomColor = `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0')}`;
return randomColor
}
function arrayOfColors(){
const arrayOfColors = [...Array(3).keys()].map(() => randomColor());
return arrayOfColors;
}
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
};
function generateColors(){
const arr = arrayOfColors();
const correctIndexColor = randomIntFromInterval(0, 2);
colorBox.style.backgroundColor = `${arr[correctIndexColor]}`;
btns.forEach((button, index) => {
button.innerHTML = `${arr[index]}`;
button.onclick = () => {
if(index === correctIndexColor)
alert('win');
else
alert('faild');
generateColors();
}
});
}
generateColors()
div {
height: 100px;
width: 100px;
}
<button></button>
<button></button>
<button></button>
<div></div>
I don't see the need to declare a arrayOfColors function, when you can just generate a random number between 1 and 3 and assign correctColor to the relative button:
const btn = document.querySelectorAll('button')
const colorBox = document.getElementById('cbox')
function randomColor(){
let randomColor = Math.floor(Math.random()*16777215).toString(16);
return randomColor
}
function generateColors(correctColor){
colorBox.style.backgroundColor = `#${correctColor}`
btn.forEach(button => button.innerHTML = `#${randomColor()}`)
// GET RANDOM NUMBER BETWEEN 1 AND 3
const rndBtnIndex = Math.floor(Math.random() * (3 - 1 + 1) + 1)
// ASSIGN THE CORRECT COLOR TO RANDOM BUTTON
document.querySelector('#btn' + rndBtnIndex).innerHTML = `#${correctColor}`
}
generateColors('ff0000')
<button id="btn1"></button>
<button id="btn2"></button>
<button id="btn3"></button>
<div id="cbox">
<p>colorBox</p>
</div>
I'm working on a project and am a bit stuck. I am sure I am missing something but have not what exactly I'm missing.
I extracted the general concept of what I'm doing and threw it onto a JS fiddle.
So basically, I am wanting to decrement the displayed number (200) by a randomly generated number between a specified number range every time the button is clicked (using vanilla JS). Got it to work a bit. When the button is clicked, it does decrement.
However I am wanting to continue to decrement it until the displayed number is 0. The issue I'm running into however is, every time the button is clicked the displayed number updates but still subtracting from 200, not from the updated value.
For example, I can click once and the number will jump from 200 down to 189. When I click again, the number will actually jump up to say 195, meaning it's subtracting from 200 rather than subtracting the new generated amount from 189.
Jsfiddle: https://jsfiddle.net/miguerurso/0wmtgd67/5/
html:
<head></head>
<body>
<div id="number" style="font-size: 2em;"></div>
<button>decrement</button>
</body>
JS:
const numberCont = document.getElementById('number');
const button = document.querySelector('button');
let x = 200;
numberCont.innerHTML = x;
button.addEventListener("click", function(){
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
const randomNumResult = randomNum(7, 12)
let updatedX = x - randomNumResult;
numberCont.innerHTML = updatedX;
})
You need assign the updateX To x as well. Currently you are only giving it to the element. Try this.
const numberCont = document.getElementById('number');
const button = document.querySelector('button');
let x = 200;
numberCont.innerHTML = x;
button.addEventListener("click", function(){
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
const randomNumResult = randomNum(7, 12)
x = Math.floor(0, x - randomNumResult);
numberCont.innerHTML = x;
}
You're not actually changing the value of x to the new subtracted value. You'll have to do this to keep subtracting from the variable. I rewrote your event listener to change the value of x without going below 0.
button.addEventListener("click", function(){
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
x = Math.max(x - randomNum(7, 12), 0);
numberCont.innerHTML = x;
})
Just change one line of code:
let updatedX = x - randomNumResult;
numberCont.innerHTML = updatedX;
with:
x = x - randomNumResult;
numberCont.innerHTML = x;
Subtract it from x instead of putting it into a new variable.
https://jsfiddle.net/sean7777/fvgchjb3/1/
Here is a quick background on project goals: I'm trying to build a simple math game that provides random math problems when you click on a button. Later, I'll figure out a way to check whether the answers are correct. I started this process by creating an input form.
I'm trying to call a random function in a javascript array using a button in HTML. The button calls a random function that is decided when I refresh the page. Once I refresh the page, the a function is randomly selected and the button continues to give the results of that function over and over. The button only calls a different function if I refresh the page.
I would prefer to have the button call a random function in my array each time the button is clicked. Anybody know how I could achieve this?
Here's my code:
const btn = document.querySelector('#START')
const randomFunc = [
multiplication,
division,
addition,
subtraction,
]
btn.addEventListener(
'click', randomFunc[Math.floor(Math.random() * randomFunc.length)]
)
function multiplication(params) {
let num1 = Math.floor(Math.random() * 13);
let num2 = Math.floor(Math.random() * 13);
let problemResult = num1 * num2;
console.log(num1, '*', num2, '=', problemResult);
document.getElementById('mathProblem').innerHTML = (`${num1} * ${num2} =`);
}
function division(params) {
let num1 = Math.floor(Math.random() * 13);
let num2 = Math.floor(Math.random() * 12) + 1;
let problemResult = (num2 * num1) / num2;
console.log(num1, '/', num2, '=', problemResult);
document.getElementById('mathProblem').innerHTML = (`${num1} / ${num2} =`);
}
function addition(params) {
let num1 = Math.floor(Math.random() * 13);
let num2 = Math.floor(Math.random() * 13);
let problemResult = num1 + num2;
console.log(num1, '+', num2, '=', problemResult);
document.getElementById('mathProblem').innerHTML = (`${num1} + ${num2} =`);
}
function subtraction(params) {
let num1 = Math.floor(Math.random() * 13);
let num2 = Math.floor(Math.random() * 13);
let numList = [num1, num2];
numList.sort(function(a, b) {
return b - a
});
let problemResult = numList[0] - numList[1];
console.log(numList[0], '-', numList[1], '=', problemResult);
document.getElementById('mathProblem').innerHTML =
(`${numList[0]} - ${numList[1]} =`);
}
<div>
<button type="button" class="btn btn-primary btn-lg" id="START">Press here for your first problem</button>
<script src={% static 'js/game_logic.js' %}></script>
<p id="mathProblem">Your problem will appear here</p>
<form action="">
<input type="text" placeholder="Type your answer here">
</form>
</div>
Wrap it in another function that selects a random function each time the click happens.
Also, your functions don't use params, so it's not needed.
const btn = document.querySelector('#START')
const randomFunc = [
multiplication,
division,
addition,
subtraction,
]
btn.addEventListener(
'click',
function() {
randomFunc[Math.floor(Math.random() * randomFunc.length)]();
}
)
function multiplication() {
let num1 = Math.floor(Math.random() * 13);
let num2 = Math.floor(Math.random() * 13);
let problemResult = num1 * num2;
console.log(num1, '*', num2, '=', problemResult);
document.getElementById('mathProblem').innerHTML = (`${num1} * ${num2} =`);
}
function division() {
let num1 = Math.floor(Math.random() * 13);
let num2 = Math.floor(Math.random() * 12) + 1;
let problemResult = (num2 * num1) / num2;
console.log(num1, '/', num2, '=', problemResult);
document.getElementById('mathProblem').innerHTML = (`${num1} / ${num2} =`);
}
function addition() {
let num1 = Math.floor(Math.random() * 13);
let num2 = Math.floor(Math.random() * 13);
let problemResult = num1 + num2;
console.log(num1, '+', num2, '=', problemResult);
document.getElementById('mathProblem').innerHTML = (`${num1} + ${num2} =`);
}
function subtraction() {
let num1 = Math.floor(Math.random() * 13);
let num2 = Math.floor(Math.random() * 13);
let numList = [num1, num2];
numList.sort(function(a, b) {
return b - a
});
let problemResult = numList[0] - numList[1];
console.log(numList[0], '-', numList[1], '=', problemResult);
document.getElementById('mathProblem').innerHTML =
(`${numList[0]} - ${numList[1]} =`);
}
<div>
<button type="button" class="btn btn-primary btn-lg" id="START">Press here for your first problem</button>
<script src={% static 'js/game_logic.js' %}></script>
<p id="mathProblem">Your problem will appear here</p>
<form action="">
<input type="text" placeholder="Type your answer here">
</form>
</div>
Your code of:
randomFunc[Math.floor(Math.random() * randomFunc.length)]
is not stored inside of a function, so as soon as the page loads and the script is initially parsed, that statement is executed and your random function name is retrieved from the array and that code will be replaced with whichever function name was gotten, so for the rest of that page's use, the code will actually be static and be evaluated like this:
// showing multiplication here, but will be whichever random name was initially returned
btn.addEventListener('click', multiplication)
But, once it's gotten, the initial randomizing code won't be executed again, because it will have already been replaced by the result of the first pass through parsing the script. So, in the end, you get one call for a random function reference and that result is what you stick with until the page is reloaded.
What you need is for that randomizing code to be executed every time the button is clicked, so by wrapping it in another function (which localizes the statement), that will happen:
btn.addEventListener(
'click', function() { randomFunc[Math.floor(Math.random() * randomFunc.length)](); }
)
Now, every time you click the button, randomFunc[Math.floor(Math.random() * randomFunc.length)] will get a new function name and () after it will cause it to be invoked because the whole expression is inside of an anonymous function expression, which will become the event handler.
it's because you're already generated a function and assigned it here
btn.addEventListener(
'click', randomFunc[Math.floor(Math.random() * randomFunc.length)]
)
in order to randomize it you have to make a callback that generates a random function instead
btn.addEventListener(
'click', function() {
const a = randomFunc[Math.floor(Math.random() * randomFunc.length)];
a();
}
)
it should now work. https://jsbin.com/duyosiluna/edit?html,js,console,output
Wrap with another function so that it gets executed on each click
btn.addEventListener('click', function () {
randomFunc[Math.floor(Math.random() * randomFunc.length)]()
})
Your code set the random function only once (on page Load) so it's always the same when clicking the button
btn.addEventListener('click', randomFunc[Math.floor(Math.random() * randomFunc.length)])
Have you tried using a arrow function, like so
btn.addEventListener(
'click', () => randomFunc[Math.floor(Math.random() * randomFunc.length)];
)
This will also execute the function on each click
The function addEventListener() adds one function to an HTML-Element when executed.
This means, when your addEventListener()-line is executed (which it only is once, when your script is executed for the first time), it selects one of your functions and adds only that.
To be able to select one of you functions repeatedly on click, you would need to instead add a function that selects on of yours, instead of adding one of yours directly. That way, the "selection"-function runs every time your button is clicked.
Here is an example:
var funcToSelect = [func1, func2, func3];
document.querySelector('button').addEventListener('click', () => {
funcToSelect[Math.floor(Math.random() * funcToSelect.length)]();
});
function func1() {
console.log('First output');
}
function func2() {
console.log('Output from second');
}
function func3() {
console.log('Yet a third output');
}
<button>Run a random function!</button>
I'm very new to code so I might not understand some answers.
I'm having trouble turning a variable into a random number between 1 and 10 in this code.
<script type="text/javascript">
var money = 0
function Random() {
money = Math.floor((Math.random() * 10) + 1);
}
</script>
I've read that I need to put return followed by the randomizing code somewhere but I just don't understand where I place that on how I use it.
function Random() {
return Math.floor((Math.random() * 10) + 1);
}
function getRandom() {
var money = Random();
console.log(money);
document.getElementById("demo").innerHTML = money;
}
<button onclick="getRandom()">Click for random number</button>
<p id="demo"></p>
This line will work:
var money = Math.floor((Math.random() * 10) + 1);
But if you want to use a function, you can write it:
var money;
function Random() {
return Math.floor((Math.random() * 10) + 1);
}
// Re-usable anytime you want
money = Random();
How can I run this every few second , without blocking the rest of the pagefrom loading.
function Create() {
var SomeArray = [];
for ( var i=0; i<=1 ; i ++) {
SomeArray[i] = (Math.random() * 10) + 1;
//alert(arr[0]);
}
return SomeArray;
}
var x = Create();
alert(x[0] + x[1]);
I was trying this var timer = setInterval(Create, 5000); it prevent loading rest of the page.
i want to get new values every few seconds
A basic example would be:
var counter = 0;
var timerRef;
var increment = function() {
counter += 1;
console.log(counter);
timerRef = setTimeout(increment, 1000);
}
setTimeout(increment, 1000);
// clearTimeout(timerRef);
Please avoid document.write refer the screencast for further details.
setInterval() can be configured to repeatedly call any function you designate at whatever time interval you request. But, you can't retrieve a return value from that function. Instead, you need to process the results from within the callback that you pass to setInterval() or call some other function and pass the results you generate inside the callback. This is how asynchronous functions work in JavaScript. I've provided several examples below of your options:
If you just want to generate two random decimal values between 1 and 10 (inclusive) every 5 seconds, you can do that like this:
var interval = setInterval(function() {
var rand1 = (Math.random() * 10) + 1;
var rand2 = (Math.random() * 10) + 1;
// now insert code here to do something with the two random numbers
}, 5000);
If you wanted the random values to be integers (which is more common), then you would do this:
var interval = setInterval(function() {
var rand1 = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
// now insert code here to do something with the two random numbers
}, 5000);
If you want to call a function and pass it those two random numbers, you can do this:
function processRandoms(r1, r2) {
// code here to do something with the two random numbers
}
var interval = setInterval(function() {
var rand1 = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
processRandoms(rand1, rand2);
}, 5000);
You can then stop the recurring interval at any time with this:
clearInterval(interval);