Decrement number by clicking button until reaching 0 - javascript

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/

Related

How can i solve this code? no errors probably bad code - javascript (array,numbers,max,min)

I am new into javascript, trying to do my uni homework.
I need to get 5 numbers into array by using input(user gets them in by himself).
Find max and min numbers from that array.
If atleast 1 number in array is bigger then 0 then divide them by max number,
if they are smaller then divide by min number.
Show answers on page
Make button that will change color of answers
I have problem with max and min numbers, also cant get point 3. work.
Other ones work properly, atleast i think so.
There is no errors in this one, but as answer he gives me only 0's, and max/min shows as +-infinity.
UPDATE:
I used answer under question and placed max/min into aprekinat() function, but works only first half of IF, code after ELSE is not working. And if u write conosle.log(max) or min it shows that max/min is not defined.
function aprekinat() {
var max = Math.max(...numbers);
var min = Math.min(...numbers);
if (numbers => 1) {
var big = document.getElementById('big');
var bigger = numbers.map(x => x / max);
document.getElementById('big').innerHTML = bigger;
} else {
var small = document.getElementById('small');
var smaller = numbers.map(x => x / min);
document.getElementById('small').innerHTML = smaller;
}
}
CODE:
var numbers = [];
function myFunction() {
numvalue = parseInt(document.getElementById('num').value);
numbers.push(numvalue);
console.log(numbers)
return false;
}
var max = Math.max(...numbers);
var min = Math.min(...numbers);
document.getElementById('apr').onclick = aprekinat;
function aprekinat() {
if (numbers => 1) {
var big = document.getElementById('big');
var bigger = numbers.map(x => x / max);
document.getElementById('big').innerHTML = bigger;
} else {
var small = document.getElementById('small');
var smaller = numbers.map(x => x / min);
document.getElementById('small').innerHTML = smaller;
}
}
document.getElementById('color').onclick = changeColor;
var currentColor = "black";
function changeColor() {
if (currentColor == "black") {
document.body.style.color = "red";
currentColor = "red";
} else {
document.body.style.color = "black";
currentColor = "black";
}
}
<html>
<head>
<title>Ld_js_5</title>
</head>
<body>
<form onsubmit="return myFunction()">
<input type="text" id="num">
<input type="submit" value="Submit">
</form>
<p id="big"></p>
<p id="small"></p>
<button id="apr">Aprekinat!</button>
<button id="color">Color!</button>
</body>
</html>
You're having you've placed the min() and max() calculations outside of any function, so they are calculating as soon as the page loads when the array is still empty.
Are they supposed to calculate when you press the "Aprekinat!" button? If so, you'll need to place lines 10 and 11 in your JavaScript inside of your aprekinat() function, before the if/then statement. That way min and max will be re-evaluated every time you calculate.

Conflict when trying to generate two separate numbers

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);

How to trigger a function repeatedly

I am working on a randomising function for a game in javascript and jquery. I have written this to randomise the position of a square in a 8x8x64px grid, and give the player a point when their character moves over it. The function works once, but wont repeat.
The relevant script
Every time the player moves it searches for
if (xNum==ptX && yNum==ptY) {
getPoint();
pointRand();
}
yNum and xNum is the player's coordinates and ptY and ptX is the point's. Movement occurs on keyUp for the arrow keys, and the if is also executed then.
Corresponding functions
//Score
var ptAllow = true;
var pt = 0;
var ptX = 7;
var ptY = 7;
var yPt = ptX*64+"px";
var xPt = ptY*64+"px";
function getPoint() {
if (ptAllow == true) {
pt++;
document.getElementById("scoreCounter").innerHTML = "score: "+pt;
document.getElementById("scoreFin").innerHTML = "score: "+pt;
}
}
function pointRand() {
ptX = Math.floor(Math.random() * 8) + 1;
ptY = Math.floor(Math.random() * 8) + 1;
ptX--;
ptY--;
yPt = ptX*64+"px";
xPt = ptY*64+"px";
$("#point").animate({"left": xPt, "top": yPt}, 100);
}
Like I said, It works perfectly the first time you move over a point, but after that nothing happens. . ptAllow is set to false once the player hits an obstacle, and the game is over.
Edit: There are no errors in the browser console, and the reason for adding and subtracting in pointRand() is that math.floor does not seem to work with a lowest value of zero.

Generating Two Numbers With a Specific Sum

I'm trying to generate two numbers with a specific sum. Here is my proposed method:
Edited: http://jsfiddle.net/KDmwn/274/
$(document).ready(function () {
function GenerateRandomNumber() {
var min = -13, max = 13;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return random;
}
var x = GenerateRandomNumber();
function GenerateRandomNumber2() {
var min2 = -13, max2 = 13;
var random2 = Math.floor(Math.random() * (max2 - min2 + 1)) + min2;
if ((random2 + x) == 0){
return random2};
}
var xx = GenerateRandomNumber2();
There's something wrong with the if ((random2 + x) = 0) line, as the code runs perfectly fine when it's removed. How can I modify this line so that the sum of the two numbers is 0? It would be most helpful if someone could modify the Jsfiddle that I've included. Thanks!
This is invalid:
if ((random2 + x) = 0){
You cannot assign something to an expression.
You probably meant to use the comparison operator (==), like this:
if ((random2 + x) == 0){
Are you trying to make it only output a second number that, when added to the first, equals 0? Because it actually already does that - but only if it gets it on the first try (try hitting refresh at least 30 times.) You need to tell it to keep re-choosing (looping) the second random number while the sum isn't 0:
function GenerateRandomNumber2() {
var min2 = -13,
max2 = 13;
var random2;
while ((random2 + x) !== 0) {
random2 = Math.floor(Math.random() * (max2 - min2 + 1)) + min2;
}
return random2;
}
http://jsfiddle.net/vL77hjp0/
To take this one step further, if I'm reading this right (if not ignore this) it looks like you might want to eventually choose a random sum and have it determine the required second number to be added. To do this, we would replace the 0 in our "while" loop with 'sum'. And 'sum' would have to be defined as a random number with a "max=x+13" and "min=x-13" (otherwise the random number may be too high/low for random2 to ever reach, causing the browser to crash.) [Or just remove the limits from random2.]
http://jsfiddle.net/fkuo54hc/
First, your GenerateRandomNumbers2 function returns undefined value other than in your if statement. So you need to return a value. I updated your fiddle and refactor some of your code.

Using math.random in button to set a select option?

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();

Categories

Resources