Displaying a value on chrome - javascript

Hello i am trying to create a simple button game and i cannot get the value to be displayed on my chrome window.
here is my code and i'm trying to display the amount of money by using console.log().
<button type="sheep" onclick="BuySheep(1)>
Sheep: <span id"Sheep">0</span><br />
Cost: <span id"SheepCost">10</span>
<var sheep = 0;>
function BuySheep(){
var SheepCost = Math.floor(10*Math.pow(1.1,Sheep));
if(Sheep >= SheepCost){
Sheep = Sheep + 1;
Money = Money - SheepCost;
document.getElementById('Sheep').innerHTML = Sheep;
document.getElementById('Money').innerHTML = Money;
};
var nextCost = Math.floor(10*Math.pow(1.1,Sheep));
document.getElementById('Money').innerHTML = nextCost;
window.setInterval(function(){
MoneyClick(Sheep);
console.log(Money);
}, 1000);

the main problem is that ur script is not in js section.
You should separate your html from your script.
You can write it in separate js file or include it by adding
<script type="text/javascript"src="scriptNameHere.js"></script>
in the head section or by wrapping it with tag like this
<script>
function BuySheep(x){
...
}
</script>

<button type="sheep" onclick="BuySheep(1)>
Sheep: <span id"Sheep">0</span><br />
Cost: <span id"SheepCost">10</span>
<script type="text/javascript">
var sheep = 0;
function BuySheep(){
var SheepCost = Math.floor(10*Math.pow(1.1,Sheep));
if(Sheep >= SheepCost){
Sheep = Sheep + 1;
Money = Money - SheepCost;
document.getElementById('Sheep').innerHTML = Sheep;
document.getElementById('Money').innerHTML = Money;
};
var nextCost = Math.floor(10*Math.pow(1.1,Sheep));
document.getElementById('Money').innerHTML = nextCost;
window.setInterval(function(){
MoneyClick(Sheep);
console.log(Money);
}, 1000);
</script>

I stripped down your project to bare necessities and made a Fiddle for you to work on it.
Fiddle Here
var Sheep = 0;
var Money = 100;
var SheepCost = 10;
function BuySheep() {
Sheep++;
$('#Sheep').html(Sheep);
Money = Money - SheepCost;
}
window.setInterval(function () {
console.log(Money);
}, 1000);
Apart from all the errors listed in my comments above, you were using variables that weren't even declared.

Related

How to make images appear randomly in Javascript?

I need to create a web page with a button that says "start game". When this button is clicked, 5 images I have downloaded (img1.png...img5.png) must appear randomly, one at a time, every half a second. Here is my code so far, any help would be greatly appreciated!
<html>
<head>
<script>
var rollImagesSchedule;
var rollImagesCounter;
function rollImagesAnimation(){
rollImagesCounter = 0;
rollImagesSchedule = setInterval(500);
}
function rollImages(){
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
rollImagesCounter = rollImagesCounter + 1;
if (rollImagesCounter == 10){
clearInterval(rollImagesSchedule);
}
}
</script>
</head>
<body>
<h1>Game</h1>
<button onClick="rollImagesAnimation()">Start frog game</button>
<br /><br />
<img id="display" style='width:200px; height:200px;'>
</body>
</html>
I think you're getting stuck with the way to use setInterval.
You can try to create a counter outside setInterval function, and nest all of your works inside of it. And the counter should be checked at the top.
function rollImages(){
var counter = 0;
var interval = setInterval(function () {
if (counter === 10) {
clearInterval(interval);
return;
}
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
counter++;
}, 500);
}
Then, you can edit the way to catch event rollImages:
<button onClick="rollImages()">Start frog game</button>
My English is not very good, so I might misunderstand your question. Let me answer it according to what I understand.
Your requirement is to randomly display one of the five pictures every 500 milliseconds, right? If so, you can try this idea:
Put the src of 5 pictures into an array
var imageSrcs = ["image1","image2","image3","image4","image5"];
Every 500 milliseconds, execute the following function:
function rollImages(){
// Randomly generate a random number between 0-4
int index = Math.floor(Math.random() * 5) + 1;
var theImage = document.getElementById("display");
// Use random numbers as subscripts and take values from the array
theImage.src = imageSrcs[index];
}
You can store the images name files into an array and then setInterval a random number and assign the source of an img html element:
var list = [
"image1.jpg",
"image2.jpg",
"image3.jpg",
];
var i = 0;
function changeImgs() {
var imageValue = Math.floor(Math.random() * list.length - 1) + 1;
image.src = list[imageValue];
}
setInterval(function() {
changeImgs()
}, 2000);
window.onload = changeImgs;
<img id="image" class="size">

Little mistake somewhere. Help needed

I wrote a little browser-game.
The rules are easy: you have 15 seconds to decide if you know the name written on the screen.
You have two buttons: "i know"/"give up" - depends on what you want to choose.
If you choose "give up" (or time ends) photo 1 appears. Otherwise, photo 2 will be shown.
Whole operation is looped.
Here's my question: I wanted to choose random name from array "word" every single round, so I wrote function "random_word()". I put it into "timer()", "surrender()" and "winning()" functions. But it doesn't work.
I'm just starting with programming, so I'll be grateful for possibly easiest to understand code. Thanks for all help.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<button id= "btnSurrender">give up</button>
<button id= "btnWinning">i know</button>
<p id="seconds">15</p>
<div id="photo"></div>
<script type="text/javascript">
var word = new Array(3);
word[0] = "Michael";
word[1] = "Simon";
word[2] = "Peter";
word[3] = "Mark";
function random_word(){
var randomWord = word[Math.floor(Math.random()*word.length)]
}
var btn1 = document.getElementById("btnSurrender");
var btn2 = document.getElementById("btnWinning");
var pic = document.getElementById("photo");
var secondsP = document.getElementById('seconds');
var clock = null;
btn1.addEventListener("click", surrender);
btn2.addEventListener("click", winning);
function timer () {
random_word();
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
pic.innerHTML='<img src="" alt="">';
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
}
if (seconds === 0) {
pic.innerHTML='<img src="mops bops.png" alt="">';
}
}, 1000);
}
function surrender(){
clearInterval(clock);
pic.innerHTML='<img src="mops bops.png" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}
function winning(){
clearInterval(clock);
pic.innerHTML='<img src="mopsik.jpg" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}
timer();
document.write(randomWord)
setInterval(timer, 17000)
</script>
</body>
</html>
var randomWord;
You need to arrow it at the beginning of the script, before giving a document.write
When I tested your code and set it to the "randomWord" variable at the beginning of the code, it worked; You should do the same, set the variable at the beginning of the code!

Why wont my text update? (HTML + JS)

I am trying to make text on my site update. The variable in JS does, but the text on screen doesn't. (Yes I know the code is sloppy, I get it to work and then go through and make it pretty.)
<script>
var moneyTotal = 370; //Variable for money, filled with starter money
var moneyText = String(moneyTotal); //Variable for text
var OD2Clicked = 0;
</script>
<script>document.write("<h1 class='money'>Total: $"+ moneyText + "</h1>"); //Line for updating site </script>
<script>
function Check(){ //Function that checks for radio button change
if (document.getElementById('OD2').checked & OD2Clicked==0) {
OD2Clicked = 1;
Adding(20);
console.log("Adding");
}else if(document.getElementById('OD').checked & OD2Clicked>0){
OD2Clicked = 0;
Adding(-20);
console.log("Subtracting");
}
setTimeout(function() {Check()}, 5000);
}
function Adding(m1){ //Function for adding
moneyTotal += m1;
moneyText = String(moneyTotal);
console.log(moneyTotal);
console.log(moneyText+" Text");
}
</script>
Just like I mentioned above in the comment:
Your screen write happens only once when Browser will parse all tags. You need to update your text on the screen every time you modify the value.
Would this work for you?
<script>
var moneyTotal = 370; //Variable for money, filled with starter money
var OD2Clicked = false;
var timeoutPeriod = 5000;
</script>
<script>document.write("<h1 class='money'>Total: $0</h1>"); //Line for updating site </script>
<script>
function Check(){ //Function that checks for radio button change
if (document.getElementById('OD2').checked) {
if (!OD2Clicked) {
OD2Clicked = true;
moneyTotal += 20;
console.log('Adding');
} else if (OD2Clicked) {
OD2Clicked = false;
moneyTotal -= 20;
console.log('Subtracting');
}
// Find DOM element we need to update
document
.querySelectorAll('.money')[0]
.textContent = 'Total: $' + moneyTotal;
}
setTimeout(Check, timeoutPeriod);
}
</script>

setInterval function using innerHTML not updating

I just can't seem to wrap my head around why this will not update what is displayed in the output. I've made a jsfiddle for anyone to look at.
http://jsfiddle.net/sQrn7/
and here's the code:
function getPrices(basePrice){
var dogeValue = 0.005343614; //When changed the output should change.
var postage = 0.49/dogeValue;
var sellAmount = (basePrice/dogeValue - postage) - (basePrice*0.1/dogeValue);
rounded = Math.round(sellAmount);
document.getElementById("txt").innerHTML = rounded;
}
var timer = setInterval(function() { getPrices(10) }, 1000);
Original/complete code:
<html>
<script>
var rounded = 0;
function getPrices(basePrice){
var dogeValue = <?php echo(file_get_contents("https://www.dogeapi.com/wow/?a=get_current_price")); ?>;
var postage = 0.49/dogeValue;
var sellAmount = (basePrice/dogeValue - postage) - (basePrice*0.1/dogeValue);
rounded = Math.round(sellAmount);
document.getElementById("txt").innerHTML = rounded;
}
var timer = setInterval(function() { getPrices(10) }, 1000);
</script>
<body onload="getPrices(10);">
<div id="txt"></div>
</body>
The PHP part is executed only once on page load. Take a look at the source code (right click on the page, "show source code"), you'll see the value assigned statically, since it's generated with PHP before the page is loaded into the browser. Keep in mind that Javascript and PHP are executed in separated contexts : PHP > server side, Javascript > client side.
A little help to resolve your problem : http://www.w3schools.com/ajax/.
If you take a look at the console, it will say Uncaught ReferenceError: sellAmount is not defined
The reason: you are missing space at the definition of the variable sellAmount: you wrote varsellAmount = ...
Use this, and it will work:
function getPrices(basePrice){
var dogeValue = 0.005343614; //When changed the output should change.
var postage = 0.49/dogeValue;
var sellAmount = (basePrice/dogeValue - postage) - (basePrice*0.1/dogeValue);
var rounded = Math.round(sellAmount);
document.getElementById("txt").innerHTML = rounded;
}
var timer = setInterval(function() { getPrices(10) }, 1000);
See your updated feedle here: http://jsfiddle.net/sQrn7/
EDIT: after your edited Question, see this fiddle: http://jsfiddle.net/Ne2gN/
The output is always the same, because the value of the dogeValue always stays the same. You have to change the value, in order to see a change in the output.
This is the new code:
var dogeValue = 0.005343614; //When changed the output should change.
function getPrices(basePrice){
var postage = 0.49/dogeValue;
var sellAmount = (basePrice/dogeValue - postage) - (basePrice*0.1/dogeValue);
var rounded = Math.round(sellAmount);
document.getElementById("txt").innerHTML = rounded;
dogeValue+=0.1;
}
var timer = setInterval(function() { getPrices(10) }, 1000);
Edit 2: After your question-edit, the answer stays the same - you can still define it globally:
<html>
<script>
var rounded = 0;
var dogeValue = <?php echo(file_get_contents("https://www.dogeapi.com/wow/?a=get_current_price")); ?>;
function getPrices(basePrice){
var postage = 0.49/dogeValue;
var sellAmount = (basePrice/dogeValue - postage) - (basePrice*0.1/dogeValue);
rounded = Math.round(sellAmount);
document.getElementById("txt").innerHTML = rounded;
dogeValue+=0.1; //change it
}
var timer = setInterval(function() { getPrices(10) }, 1000);
</script>
<body onload="getPrices(10);">
<div id="txt"></div>
</body>
You can place your php-Tags everywhere in your code - it doesn't matter if they are inside our outside a function. This code does exacly the same as yours, with the only difference, that getPrices() is now able to change the dogeValue.

How do you make a Variable decrease every time a button is clicked by the value of another Variable in JavaScript?

I'm trying to make a button that decreases a variable-defined number by another variable-defined number every time it's clicked.
Example:
[Button]
Number: 500
*Button Clicked
[Button]
Number: 475
*Button Clicked Again
[Button]
Number: 450
And so on..
I'd love to give code and what not but I can't even get it close to working so that would be useless..
The code could look like this:
var count = 500;
var decrementAmount = 25;
function reduceVariable() {
count -= decrementAmount;
}
Then, just call reduceVariable from your button click.
See this jsfiddle
HTML:
<div id="text">500</div>
<p><input type="button" id="button" value="Decrease me"></p>
Javascript:
var oButton = document.getElementById("button");
var oText = document.getElementById("text");
var count = 500;
oButton.addEventListener('click', function(i, a) {
oText.innerHTML = count -= 25;
}, false);
Try this as example:
HTML:
<span id="spnTest">500</span>
<button id="btnTest" >Decrease</button>
Javascript:
var ratio = 25;
var totalValue = 500;
function decrease(){
if(totalValue == 0) return;
totalValue -= ratio;
document.getElementById('spnTest').innerHTML = totalValue;
}
document.getElementById('btnTest').onclick = function(){ decrease(); }
Here is demo

Categories