Have html show up after javascript function completes - javascript

I'm attempting to create a generic game of blackjack through javascript. The game starts when you click the start button:
<button type="button" onClick="deal()">Start Game</button>
which in turn runs the method deal:
function deal() {
card1 = Math.floor(Math.random() * 52);
card2 = Math.floor(Math.random() * 52);
card1 = changeCard(card1);
card2 = changeCard(card2);
score = card1 + card2;
for (var i = 0; i < aceAmount || score > 21;aceAmount--) {
score -= 10;
}
document.write("You were dealt a " + card1 + " and a " + card2 + " for a total of " + score + ".\nDo you wish to hit or pass?");
aceAmount = 0;
};
My question is once the deal method runs, how can I get two html buttons to show up on the screen, such as:
<button type="button" onClick="hit()">Hit</button>
<button type="button" onClick="pass()">Pass</button>

What to do?
Use the CSS display property to hide your buttons, then using the getElementById, method you "select" those buttons to do some "Javascripty" stuff on them.
Your HTML
<button id="hit_btn" style="display:none;" type="button" onClick="hit()">Hit</button>
<button id="pass_btn" style="display:none;" type="button" onClick="pass()">Pass</button>
and add this to your Javascript function:
document.getElementById('hit_btn').style.display = '';
document.getElementById('pass_btn').style.display = '';
and when you want to hide them back again
document.getElementById('hit_btn').style.display = 'none';
document.getElementById('pass_btn').style.display = 'none';

you could set an id or class on the buttons, and set a css rule with display:none. At the end of the deal function, set a line which changes display to block or inline. in jQuery, it would be
$('button.hit').css({visibility: "visible"})

Related

I tried to make a simple fun system with increasing and decreasing numbers with input, but it doesnt work

I tried the script and its working well for the first 2 functions, but then when I added the third one, the entire page just doesn't work. Can I know why and how to fix?
I am a beginner Javascripter and I still need practices so can you guys explain someway suitable for my level?
let a = 0,
b = 1
function inc() {
a += b
document.getElementById("x").innerHTML = "x" + " " + "=" + " " + a;
};
function dec() {
a -= b
document.getElementById("x").innerHTML = "x" + " " + "=" + " " + a;
};
function input() {
if (document.getElementById("input").innerHTML == null) {
} else {
b = Number(document.getElementById("input").innerHTML);
};
};
body {
background-color: powderblue;
}
<h1>Online simple Javascript project!</h1>
<p id="x">x = 0</p><!-- Result -->
<p><br><br>Change the power here!</p><!-- // Description -->
<input id="input"><button type="button" onclick="input()">Apply</button><!-- // Button that save your power -->
<h2>Click the button to increase x</h2><!-- // Description -->
<button type="button" onclick="inc()">Increase</button><!-- // Increase -->
<h2>Click the button to decrease x</h2><!-- // Description -->
<button type="button" onclick="dec()">Decrease</button><!-- // Decrease -->
Use value instead of innerHTML for input
function input() {
if (document.getElementById("input").value != null){
b = Number(document.getElementById("input").value);
};
};

How to push score into an array, then display it

I'm trying to make a dice game where the goal for each of participants is to collect points as fast as possible to pass 100. Each participant can throw the die as many times as they want and add the points, but achieved points within a certain game fall away if a one is rolled. For example, if you have 15 points in a game and have stopped in time, these points can be taken further to round two. These points cannot be lost in a later round and thus become included in the summary.
I've managed to:
write the code that shows images of dice and sums up the current score (images = 1.png, 2.png etc).
Resets the current score to 0 when the player rolls a one.
What I need help with is how to write the code that activates the button "done for now" and takes that value and pushes it into an array(????) then clears the score for the next round -> then displaying the score on the site while the other rounds keep on going. It should also sum up the score and throws from each round (first to 100).
Here is my code:
var points = 0;
var start, dice, print;
window.onload = run;
function $(id) {
return document.getElementById(id);
}
function run() {
start = $("throwDice");
dice = $("dice");
print = $("print");
start.onclick = throwDice;
}
function throwDice() {
var throwD = Math.floor(Math.random() * 6) + 1;
throwD.innerHTML = '<img width="20%" src="' + throwD + '.jpg">';
add(throwD);
}
function add(value) {
points += value;
if (value == 1) {
points = 0;
$("print2").innerHTML = "GAME OVER"
} else {
$("print2").innerHTML = "";
$("print").innerHTML = points;
}
}
<div class="round">
<h1>The endless road</h1>
<button id="throwDice">Throw Dice</button> <button>Done for now</button>
<div id="dice" class="dice"></div>
<h2 id="print"></h2>
<p id="print2"></p>
</div>
Basically you just have to add another click event listener to the 'Done for now' button whose callback function
pushes the current points to an array
resets the points to 0
updates the text elements on screen
Something like:
var points = 0;
var pointsArray = new Array();
var start, dice, print;
function $(id) {
return document.getElementById(id);
}
function run() {
start = $("throwDice");
dice = $("dice");
print = $("print");
start.onclick = throwDice;
done = $("done");
done.onclick = stopRound;
}
function stopRound() {
pointsArray.push(points);
points = 0;
$("print").innerHTML = points;
$("print3").innerHTML = pointsArray;
}
function throwDice() {
var throwD = Math.floor(Math.random() * 6) + 1;
throwD.innerHTML = '<img width="20%" src="' + throwD + '.jpg">';
add(throwD);
}
function add(value) {
points += value;
if (value == 1) {
points = 0;
$("print2").innerHTML = "GAME OVER"
} else {
$("print2").innerHTML = "";
$("print").innerHTML = points;
}
}
run();
<div class="round">
<h1>The endless road</h1>
<button id="throwDice">Throw Dice</button> <button id="done">Done for now</button>
<div id="dice" class="dice"></div>
<p id="print3" style="float:right;"></p>
<h2 id="print"></h2>
<p id="print2"></p>
</div>

How to apply class function on id function?

So I have a task to make function (show/hide) for every paragraph (five of them) and I did like so
function btn() {
var x = document.getElementById('para');
if (x.style.display == "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
For every paragraph I used Id instead of class. Because task said one button per one paragraph.
Now I have a problem how to apply this (color) function for all of them in the same time.
function color() {
bgColorCode = '#' + Math.floor((Math.random() * 999999) + 100000);
elements = document.getElementByClassName('color');
for (var i = 0; i < elements.length; i++) {
document.getElementByClassName('color')[i].style.backgroundColor = bgColorCode;
}
}
//Html
<button onclick = "color()">Color</button>
<button onclick = "btn()">Show/Hide</button>
<p id = "para"> Example 1 </p>
<button onclick = "btn2()">Show/Hide</button>
<p id = "para2"> Example 2 </p>
...
Idk how to apply this function "color" to all of my paragraphs because they are under id?
Any solutions?
If you add the class color to your para elements and change the function getElementByClassName() to getElementsByClassName() (you forgot an s). then your code works. Within the for loop you can use the elements array elements[i] instead of another call to the getElementsByClassName() function.
function color() {
bgColorCode = '#' + Math.floor((Math.random() * 999999) + 100000);
elements = document.getElementsByClassName('color');
for (var i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = bgColorCode;
}
}
//just slightly modified so it works with multiple paragraphs by making the id a function parameter.
function btn(id) {
var x = document.getElementById(id);
if (x.style.display == "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button onclick="color()">Color</button>
<button onclick="btn('para')">Show/Hide</button>
<p class="color" id="para">Example 1</p>
<button onclick="btn('para2')">Show/Hide</button>
<p class="color" id="para2">Example 2</p>
Hope this is what you want. Tell me if you have doubts.
The function toggleshow(htmlObj) selects next element sibling of element which triggered the function with an argument this which represent the current HTMLelement and if the value of style.display is set to none, then it changes it value to block else change it to none.
see HTML DOM manipulation
The second function color() takes advanced parameters that is (string)id of HTML element, and loops through all arguments passed and change bgcolor for every id. You can pass many arguments as you want.
see this
document.querySelector('css selector') selects first html element using css selectors
function toggleshow(htmlObj){
var par = htmlObj.nextElementSibling;
if(par.style.display !== 'none'){
par.style.display = 'none';
}else{
par.style.display = 'block';
}
}
function color(){
bgColorCode = '#' + Math.floor((Math.random() * 999999) + 100000);
for (var i = 0; i < arguments.length; i++) {
document.querySelector('#'+arguments[i]).style.backgroundColor = bgColorCode;
}
}
button{
display:block
}
<button onclick = "color('para', 'para2', 'para3', 'para4', 'para5')">Color</button>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para"> Example 1 </p>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para2"> Example 2 </p>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para3"> Example 2 </p>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para4"> Example 2 </p>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para5"> Example 2 </p>
*sorry for my bad English and spelling mistakes.
A better and more dynamic solutions with JQUERY:
*If you don't know how to use Jquery then you can check Mark Baijens answer.
function btn(e) {
if ($(e).next().css('display') == "none") {
$(e).next().show()
$(e).html("Hide")
} else {
$(e).next().hide()
$(e).html("Show")
}
}
function color() {
bgColorCode = '#' + Math.floor((Math.random() * 999999) + 100000);
//elements = document.getElementByClassName('color');
$(".para").css("background-color",bgColorCode)
}
<div>
<button onclick = "color()">Color</button>
</div>
<hr>
<div id="wrapper">
<button onclick = "btn(this)">Show/Hide</button>
<p class="para"> Example 1 </p>
<hr>
<button onclick = "btn(this)">Show/Hide</button>
<p class="para"> Example 2 </p>
<hr>
<button onclick = "btn(this)">Show/Hide</button>
<p class="para"> Example 3 </p>
<hr>
<button onclick = "btn(this)">Show/Hide</button>
<p class="para"> Example 4 </p>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

I can't get setInterval to work for me

I have a function called start that is triggered when you push the start button. The start function calls another function called getRandomImage. I want getRandomImage to repeat every 5 seconds, but I just can't get the setInterval method to work for me. I've tried putting the interval on the start function, but that just causes it to fire off once, and doesn't repeat. I've tried putting the interval on the getRandomImages function, but then it doesn't do anything. Essentially I am trying to make a color blindness test that flashes a random image every 5 seconds until 30 images have passed or the user clicks a button. I've been banging my head against this for over 8 hours, and am really questioning my choice in programming languages right now, lol.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"
<title></title>
<link rel="stylesheet" href="ColorPerceptionTest.css">
</head>
<body>
<section>
<img src="Default.png" id="defaultimage">
<form>
<input type="button" id="Button1" value="" onClick="">
<input type="button" id="Button2" value="" onClick="">
<input type="button" id="Button3" value="" onClick="">
<br>
<input type="button" id="Start" value="Start" onClick="start()">
<input type="button" id="Help" value="Help" onClick="help()">
<br>
<p id="help"> </p>
</form>
</section>
<script>
var $ = function(id) {
return document.getElementById(id);
}
$("Button1").style.display = "none";
$("Button2").style.display = "none";
$("Button3").style.display = "none";
var imagesArray = ["3.gif", "05.gif", "5.gif", "6.gif", "7.gif",
"8.gif", "12.gif", "15.gif", "16.gif", "26.gif",
"29.gif", "42.gif", "45.gif", "73.gif",
"74.gif"];
var runTimer = setInterval(start, 5000);
function getRandomImage(imgAr, path) {
path = path || 'images/';
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
$("defaultimage").src = path + img;
$("Button1").style.display = "initial";
$("Button2").style.display = "initial";
$("Button3").style.display = "initial";
if(parseInt(img) < 8){
$("Button1").value = parseInt(img);
$("Button2").value = parseInt(img) - 2;
$("Button3").value = parseInt(img) + 1;
}else if(parseInt(img) > 7 && parseInt(img) < 29){
$("Button1").value = parseInt(img) - 2;
$("Button2").value = parseInt(img);
$("Button3").value = parseInt(img) + 1;
}else{
$("Button1").value = parseInt(img) - 5;
$("Button2").value = parseInt(img) - 9;
$("Button3").value = parseInt(img);
}
}
var start = function(){
$("help").innerHTML = "";
getRandomImage(imagesArray);
$("Start").style.display = "none";
$("Help").style.display = "none";
}
var help = function (){
$("help").innerHTML = "This is a test designed to help you determine" +
" if you have a problem with seeing colors. When you press start, a series of " +
"random images will be displayed. You have 5 seconds to read the number and " +
"select the correct button.";
}
</script>
</body>
Try moving the setInterval call to a point where start is defined...
Your code works fine in this fiddle.
var start = function(){
$("help").innerHTML = "";
getRandomImage(imagesArray);
$("Start").style.display = "none";
$("Help").style.display = "none";
}
var runTimer = setInterval(start, 5000);
Update: To make it more clear, had OP written function start() the posted code would have been properly hoisted. But, as he used a function expression, start is undefined when setInterval is called.
Another update: Here's a forked fiddle to correct the timer based on the button and the comments below.

How do I call a function that enters text into a read-only text-box by clicking an HTML button?

I am trying to write a short piece of html code that, given two initial amounts, attempts to find the number greater than or equal to the first that wholly divides the second given amount. The code tries to divide the numbers, and if it is unsuccessful, adds 1 to the first number and tries to divide again, etc...
I want the code to return the value that does wholly divide the second number AND the answer to the division (with some plain text appearing around it).
Added to this, or at least I'd like there to be, is that upon clicking one of 5 different buttons a multiplication operation is performed on the first given number, it is rounded up to the nearest whole number, and THEN the function attempts to divide this into the second given number.
It's difficult to explain exactly what I want without showing you the code I have so far, so here it is:
<html>
<head>
<b>Rounded Commodity Pricing:</b><br>
</head>
<script language="Javascript">
var currency;
function setCurrency(val) {
var currency = val;
}
function finddivid(marketprice,tradevalue) {
var KWDex = 0.281955
var GBPex = 0.625907
var USDex = 1
var CADex = 0.998727
var EURex = 0.784594
if
(currency == "KWD")
var currencyMarketprice = Math.ceil(marketprice*KWDex);
else if
(currency == "GBP")
var currencyMarketprice = Math.ceil(marketprice*GBPex);
else if
(currency == "USD")
var currencyMarketprice = Math.ceil(marketprice*USDex);
else if
(currency == "CAD")
var currencyMarketprice = Math.ceil(marketprice*CADex);
else if
(currency == "EUR")
var currencyMarketprice = Math.ceil(marketprice*EURex);
if (tradevalue % currencyMarketprice == 0)
return ("tonnage = " + tradevalue / currencyMarketprice + " mt, and price = " + currencyMarketprice +" " +currency +" per mt");
else
{for (var counter = currencyMarketprice+1; counter<(currencyMarketprice*2); counter++) {
if (tradevalue % counter == 0)
return ("tonnage = " + tradevalue / counter + " mt, and price = " + counter +" " +currency +" per mt");}}
}
</script>
</head>
<p>Select currency:
<input type="button" value="KWD" OnClick="setCurrency('KWD')">
<input type="button" value="USD" OnClick="setCurrency('USD')">
<input type="button" value="GBP" OnClick="setCurrency('GBP')">
<input type="button" value="EUR" OnClick="setCurrency('EUR')">
<input type="button" value="CAD" OnClick="setCurrency('CAD')">
<P>Enter today's price of commodity in USD: <input name="mktprc" input type="number"><br><p>
<P>Enter value of trade: <input name="trdval" input type="number">
<input type="button" value="Calculate" OnClick="document.getElementById('showMeArea').value=finddivid(document.getElementById('mktprc'),document.getElementById('trdval')));">
<p>
<br><br>
<input name="showMeArea" readonly="true" size="100">
</html>
If you run this html in your browser you should see what I am trying to achieve.
I've tried for a while to get this to work and I don't know if the error if in the function or it the way I am trying to get the 'return' of the function 'finddivid' into the text box 'showMeArea'...
Here are the main problems/features that I need help with:
I would like to be able to click on one of the 'currency' buttons so that upon clicking, the variable 'currency' is assigned and then used in the function finddivid.
(2. This isn't as important right now, but eventually, once this is working, I'd like it so that upon clicking one of the currency buttons, it changes colour, or is highlighted or something so that the user knows which currency rate they are using.)
Upon entering the numbers into the two boxes I would like to click 'Calculate' and have it return what I've written in the function into the 'showMeArea' read-only box at the end of the code.
I know I'm probably missing loads of stuff and I might be miles away from success but I am very new to programming (started just a few days ago!) so would like any kind of help that can be offered.
Thanks in advance of your comments.
There are quite a few things wrong with your markup and javascript. You have unclosed paragraph tags, you set the scope of currency to be global but then define a local variable with the same name when you want to set it (which is why currency is never being set globally), you're using an if/else statement where a switch/case is more appropriate... there's probably a lot more, and the more you learn the more you'll discover. Having said all that, because it bothered me, here's a modified version of your code which seems to do what you were after :
<html>
<head>
<title>Rounded Commodity Pricing</title>
<script type="text/javascript">
var currency;
function setCurrency(val) {
currency = val;
}
function finddivid(marketprice, tradevalue) {
var KWDex = 0.281955
var GBPex = 0.625907
var USDex = 1
var CADex = 0.998727
var EURex = 0.784594
var currencyMarketprice;
switch (currency) {
case "KWD":
currencyMarketprice = Math.ceil(marketprice * KWDex);
break;
case "GBP":
currencyMarketprice = Math.ceil(marketprice * GBPex);
break;
case "USD":
currencyMarketprice = Math.ceil(marketprice * USDex);
break;
case "CAD":
currencyMarketprice = Math.ceil(marketprice * CADex);
break;
case "EUR":
currencyMarketprice = Math.ceil(marketprice * EURex);
break;
}
if (tradevalue % currencyMarketprice == 0)
return ("tonnage = " + tradevalue / currencyMarketprice + " mt, and price = " + currencyMarketprice + " " + currency + " per mt");
else {
for (var counter = currencyMarketprice + 1; counter < (currencyMarketprice * 2); counter++) {
if (tradevalue % counter == 0)
return ("tonnage = " + tradevalue / counter + " mt, and price = " + counter + " " + currency + " per mt");
}
}
}
function calculate() {
var mktprc = document.getElementById('mktprc');
var trdval = document.getElementById('trdval');
document.getElementById('showMeArea').value = finddivid(mktprc.value, trdval.value);
}
</script>
</head>
<p>
Select currency:
<input type="button" value="KWD" onclick="setCurrency('KWD')">
<input type="button" value="USD" onclick="setCurrency('USD')">
<input type="button" value="GBP" onclick="setCurrency('GBP')">
<input type="button" value="EUR" onclick="setCurrency('EUR')">
<input type="button" value="CAD" onclick="setCurrency('CAD')">
</p>
<p>Enter today's price of commodity in USD: <input id="mktprc" input type="number"><p>
<p>Enter value of trade: <input id="trdval" input type="number"></p>
<p><input type="button" value="Calculate" OnClick="calculate();"></p>
<p>
<input id="showMeArea" readonly="true" size="100">
</p>
</html>

Categories

Resources