Celsius to Fahrenheit conversion- JavaScript - javascript

I'm making Celcius to Farenheit calculater. My codepen is here: https://codepen.io/j9k9/pen/zBZJQL
I'm trying to make it so that if the celcius input is active, the convert to farenheit function is called and vice versa and for the conversion to happen only when the submit button is clicked.
I also tried an if/else statement for the active form id which did not work.
Code is as follows:
HTML:
<html>
<head>
<meta charset="UTF-8">
<title>Temperature Converter - Part 1</title>
</head>
<body>
<h1>Temperature Converter</h1>
<div id="inputs">
<input id="cInput" placeholder="celcius"/>
<input id="fInput" placeholder="farenheit"/>
</div>
<button id="submit">Convert</button>
<h1 id="result">Result:</h1>
<script src="js/index.js"></script>
</body>
</html>
JS:
document.getElementById("cInput").oninput = function() {convertCToF()};
document.getElementById("fInput").oninput = function() {convertFToC()};
function convertCToF() {
var c = document.querySelector("#cInput").value;
var f = c * (9 / 5) + 32;
c = parseInt(c);
f = parseInt(f);
document.querySelector("#result").innerHTML = ("Result: ") + f + (" \u2109");
}
document.querySelector("#submit").onclick = convertCToF;
function convertFToC() {
var f = document.querySelector("#fInput").value;
var c = (f - 32) * 5 / 9;
c = parseInt(c);
f = parseInt(f);
document.querySelector("#result").innerHTML = ("Result: ") + c + (" \u2103");
}
document.querySelector("#submit").onclick = convertFToC;

I had corrected your code-pen and noted as to where, why and what could be improved but someone appears to have deleted my comment. As there isn't a concrete answer yet I'll transfer it here.
Remove these two lines if you don't want it to update on the fly:
document.getElementById("cInput").oninput = function() {convertCToF()};
document.getElementById("fInput").oninput = function() {convertFToC()};
Instead decide which "mode" of conversion the script will run based on the last input box used.
var conversionFn;
document.querySelector('#cInput').onfocus = function(){
conversionFn = convertCToF;
};
document.querySelector('#fInput').onfocus = function(){
conversionFn = convertFToC;
};
Note: that in your conversion functions the following lines are useless (remove them).
c = parseInt(c);
f = parseInt(f);
When used in expressions, variables will be coerced to a Number where appropriate - where you wish to be explicit you should do this conversion before you perform a calculation with the value.
ยป see also: Javascript Unary Operator as another example of this.
Next setup a listener for your button, note that you cannot simply attach the conversionFn to the event handler itself as this will assign a single unchanging reference (or undefined) immediately which is of no use - instead, encapsulate the variable in the scope of a new function closure.
document.querySelector('#submit').onclick = function(){
conversionFn();
};

Please use these functions instead.
function getFahrenheitFromCelsius(celsius){
return (celsius * (9 / 5)) + 32;
}
function getCelsiusFromFahrenheit(fahrenheit){
return (fahrenheit - 32) * (5 / 9);
}

https://codepen.io/anon/pen/mEvzOV
I have written this just for your demo
function getElm(id){
return document.getElementById(id);
}
function readValue(id){
return getElm(id).value;
}
function updateHtml(text,id){
getElm(id).innerHTML = text;
}
function convertCToF(c) {
var f = c * (9 / 5) + 32;
return f;
}
function convertFToC(f) {
var c = (f - 32) * 5 / 9;
return c;
}
function sequnce(){
var val = readValue(activeId);
var convertedVal = activeFn(val);
updateHtml("Result: "+ convertedVal + activeSuffix,'result')
}
var activeFn = convertCToF;
var activeId = 'cInput';
var activeSuffix = "โ„‰"
getElm('cInput').onfocus = function(){
activeFn = convertCToF;
activeId = 'cInput';
activeSuffix = "โ„‰"
}
getElm('fInput').onfocus = function(){
activeFn = convertCToF;
activeId = 'fInput';
activeSuffix = "โ„ƒ"
}
getElm("cInput").oninput = sequnce;
getElm("fInput").oninput = sequnce;
getElm("submit").oninput = sequnce;

Related

How to solve a linear equation with algebra.js?

I'm trying to solve/evaluate an equation using algebra.js by nicolewhite and can't seem to get it right.
Here's the code i'm using:
<!DOCTYPE html>
<html>
<head>
<script src="//algebra.js.org/javascripts/algebra-0.2.6.min.js"></script>
</head>
<body>
<script>
var Fraction = algebra.Fraction;
var Expression = algebra.Expression;
var Equation = algebra.Equation;
var x1 = algebra.parse("1/5 * x + 2/15");
var x2 = algebra.parse("1/7 * x + 4");
var eq = new Equation(x1, x2);
console.log(eq.toString());
var answer = eq.solveFor("x");
console.log("x = " + answer.toString());
</script>
</body>
I'm not sure linking the source js works here but it just gives me a blank page anywhere i try that code. I have defined the three variables as stated by the algebra author so I'm not sure what i'm doing wrong.
You are getting a blank page because you are not setting the answer to any html element. Your code is sending the output to the console so you should be able to see it there.
Try this to show the result on your page.
var Fraction = algebra.Fraction;
var Expression = algebra.Expression;
var Equation = algebra.Equation;
var x1 = algebra.parse("1/5 * x + 2/15");
var x2 = algebra.parse("1/7 * x + 4");
var eq = new Equation(x1, x2);
console.log(eq.toString());
var answer = eq.solveFor("x");
console.log("x = " + answer.toString());
const output = document.createElement('p');
document.body.appendChild(output);
output.textContent = "x = " + answer.toString();

How to create Javascript Blackjack

I'm having trouble creating a Blackjack program to display in an HTML page using an external Javascript file.
I don't need to label my cards, and I've created a dealer that will always be between 17-21 in score.
I'm unsure of what parts of my code is completely wrong and what needs a bit of tweaking. I believe I've done something that has broken the program.
EDIT: I've edited some of the fixes that many of you have helped with, an error I get when running the program is that if I do use an alert to display the score/outcome, the alert does not appear when running.
My goal is to display my the score/cards from my Javascript code into my HTML code which looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Blackjack</title>
<link rel="stylesheet" type="text/css" href="CSSedit.css">
</head>
<body>
<script type="text/javascript" src="Blackjack.js">
</script>
<h1>Javascript Blackjack</h1>
<p>Player's Hand: </p>
<br>
<p>Dealer's Score: </p>
<p>Player's Score: </p>
<br>
<p>Game Results: </p>
</body>
</html>
My javascript code:
//function that returns a random card
var deal = function() {
card = Math.floor(Math.random()*52+1);
return card;
};
//function that returns dealers hand between 17-21
var dealerhand = function(x, y) {
cardDealer = Math.floor(Math.random()*(21 - 17 + 1)+17);
return cardDealer;
}
//declaring variables
var card1 = deal();
var card2 = deal();
var dealer = dealerhand();
var x = 17;
var y = 21;
//retrieving the value of the cards from the deal function
var getValue = function(card) {
if(card % 13 === 0 || card % 13 === 11 || card % 13 === 12){
return 10;
}
if(card % 13 === 1){
return 11;
}
else{
return card % 13;
}
}
//scoring the cards dealt and determining the outcome
//using the if and else if statements
function score() {
if ((getValue(card1) + getValue(card2)) > 22){
return "Busted!";
}
else if (getValue(cardDealer) > getValue(card1) + getValue(card2)){
return "You lose!";
}
else if (getValue(cardDealer) === getValue(card1) + getValue(card2)){
return "Draw!";
}
else{
return getValue(card1) + getValue(card2);
}
}
//Need to display results onto HTML page
//alert("You have card " + card1 + " / " + card2 +
// " Score: " + score(card1, card2);
You have a syntax error on your deal function
//function that returns dealers hand between 17-21
var dealerhand = function(17, 21) {
card = Math.floor(Math.random()*(21 - 17 + 1)+17);
return cardD; //should be return card;
}
Use the console in your browser (accessible through dev tools) to help spot errors in your application, errors like this show up bright as day.
There is a syntax error on line 14:
var dealerhand = function(17, 21) {
...
You can only pass variables as arguments to a function and 17 and 21 are not variables. An easy fix would be:
var a = 17;
var b = 21;
var dealerhand = function(a, b) {
...
Hopefully ES6's argument defaults will clear some confusion in this area.
Edit:
You have another error on line 41:
if (getValue(card1) + getValue(card2) > 22{
Should be
if ((getValue(card1) + getValue(card2)) > 22) { ... }
Edit 2:
An another one. Functions should be declared before using references in the variables and thus these two functions should come before your declaring variables comment.
// function that returns a random card
var deal = function() {
card = Math.floor(Math.random()*52+1);
return card;
};
// function that returns dealers hand between 17-21
var dealerhand = function(a, b) {
card = Math.floor(Math.random()*(21 - 17 + 1)+17);
return cardD;
}

Button to randomize pictures won't work the second time

var fnr = function (a,b) {
// random integer on closed interval
var y = a + Math.floor((b - a + 1) * Math.random());
return y
}
var foo;
var myTimer;
function toRandom() {
var x = fnr(0, PICTURES.length - 1);
var y = SERVER + FOLDER + PICTURES[x] + SUFFIX;
document.getElementById("img").src = y;
document.getElementById("filename").value = PICTURES[x].toUpperCase();
}
function toRandomize() {
if(!foo) {
foo = true;
document.getElementById("random").value = "stop shuffle";
myTimer = setInterval("toRandom()", 600);
} else {
foo = false;
document.getElementById("random").value = "start shuffle";
clearInterval(myTimer);
}
}
window.onload = function () {
document.getElementById("random").onclick = toRandomize;
}
// button in the body of the HTML portion of my code
<input id="random" type="button" value="start shuffle">
I have a button to randomize photos, but it won't work the second time. Do you guys have any insight in reading the code? I know fnr stands for first-non-repeating, but I'm not too familiar with how to "reset it," or if it requires a reset to get it to work again. I have the same setup for other functions and they work fine.
It's cut so it will only show the parts relevant to the question. I apologize if it's confusing.

Generating a random color not working

I was working on a simple project, to have the background of a webpage change every time you click on it. I succeeded in such, tested it a few times, save, tested again, and then left.
I go home and load it.. And it no longer works. I am using the same browser, I have no idea how anything could have changed.. I must have messed up a few ways almost impossible it feels like.. But alas, I'm sitting here dumb-founded..
Could anyone take a look at my simple program and tell me what is wrong? (Again, the program purpose is to change the webpage's background color to a random color whenever you click on the page.)
Here is the code:
<!DOCTYPE HTML PUBLIC>
<html>
<head>
<title>Random Colors</title>
<script language="javascript">
function randomColor() {
var h0 = Math.floor(Math.random()*99);
var h1 = Math.floor(Math.random()*99);
var h2 = Math.floor(Math.random()*99);
var h3 = Math.floor(Math.random()*99);
var h4 = Math.floor(Math.random()*99);
var h5 = Math.floor(Math.random()*99);
return '#'.toString(16)+h0.toString(16)+h1.toString(16)+h2.toString(16);+h3.toString(16)+h4.toString(16)+h5.toString(16);
}
</script>
</head>
<body onclick="document.bgColor=randomColor();">
</body>
</html>
Thanks in advance if anyone can help.
Having '#'.toString(16) makes no sense, the string '#' can't be converted to a string in hexadecimal form...
You have an extra semicolon after h2.toString(16).
return '#'+h0.toString(16)+h1.toString(16)+h2.toString(16)+h3.toString(16)+h4.toString(16)+h5.toString(16);
I think that you want to keep each digit in the range 0-15 instead of 0-98:
var h0 = Math.floor(Math.random()*16);
Try this out. Built off of what #Guffa did
function randomColor() {
var h0 = Math.floor(Math.random()*16);
var h1 = Math.floor(Math.random()*16);
var h2 = Math.floor(Math.random()*16);
var h3 = Math.floor(Math.random()*16);
var h4 = Math.floor(Math.random()*16);
var h5 = Math.floor(Math.random()*16);
return '#' + h0.toString(16) + h1.toString(16) + h2.toString(16) + h3.toString(16) + h4.toString(16) + h5.toString(16);
}
Here's the fiddle --> http://jsfiddle.net/Jh5ms/1/
Is there a reason you're using Math.random so many times?
function pad6(s) {
s = '' + s;
return '000000'.slice(s.length) + s;
}
function randomColor() {
var rand = Math.floor(Math.random() * 0x1000000);
return '#' + pad6(rand.toString(16)).toUpperCase();
}
randomColor(); // "#7EE83D"
randomColor(); // "#19E771"
As pointed out by Guffa, your first error was attempting to convert '#' to a hexadecimal representation.
This should do the trick:
function randomColor() {
var ret = Math.floor(Math.random() * (0xFFFFFF + 1)).toString(16);
return ('#' + new Array((6 - ret.length) + 1).join('0') + ret);
}
window.onload = function() {
document.querySelector('button').onclick = function() {
document.querySelector('body').style.backgroundColor = randomColor();
};
};
Here is a demonstration.
Here is another demonstration showing how you could implement it into your current page. I also took the liberty of changing your event handler to be unobtrusive.
Adding to Guffa fixing the Math.random()*99 problem, I would put all this in a loop like this:
var theColor = "#";
for (var i = 0; i < 6; i++) {
theColor += Math.floor(Math.random() * 16).toString(16);
}
return theColor;
Here's a jsFiddle
another answer in your format - pass this to whatever you want to change backgroundcolor
http://jsfiddle.net/FpLKW/2/
<div onclick="test(this);">
</div>
function test (ele) {
var h0 = Math.floor(Math.random()*10);
var h1 = Math.floor(Math.random()*10);
var h2 = Math.floor(Math.random()*10);
var h3 = Math.floor(Math.random()*10);
var h4 = Math.floor(Math.random()*10);
var h5 = Math.floor(Math.random()*10);
var x = '#' + h0.toString(16) + h1.toString(16) + h2.toString(16) + h3.toString(16) + h4.toString(16) + h5.toString(16);
ele.style.backgroundColor=x;
}

Taking var with JS prompt - how can I make it through HTML form?

I've been learning HTML/CSS/JavaScript for a couple of weeks now, and I am currently practicing on a mini project, which consists of letting people answer math questions, and validating their answers.
My current progress can be seen at http://dany.faceflow.com
I know I am probably not using the best strategy to develop this mini game, so any advice would be useful on that. However right now, the problem is that I am taking the user answer with a variable through JS prompt, and I want to do it via an HTML form (less annoying).
In my source code you can see this line within the function:
var userInput = prompt(numb1 + symbol + numb2);
Then, still in the same function, I have an if/else structure to compare the user's answer with the right answer. The code works, I just don't know how to make the prompt HTML-based instead. I've tried an html form with an ID and in the JS using getElementById, document.write and some other stuff but I never got it to work for that part.
(Here's all the JS)
var number1 = function() {
var numb1 = Math.floor(Math.random() * 41) + 10;
return numb1;
}
var number2 = function() {
var numb2 = Math.floor(Math.random() * 41) + 10;
return numb2;
}
var userAnswer = function() {
var numb1 = number1();
var numb2 = number2();
var randomSymbol = Math.random();
if (randomSymbol > 0.5) {
var symbol = "+";
} else {
var symbol = "-";
}
// add the math question in the html bubble
document.getElementById('bubble').innerHTML = numb1 + symbol + numb2;
// Prompts the user to give an answer. Change this to HTML.
var userInput = prompt(numb1 + symbol + numb2);
//var userInput = document.getElementById('tw').value;
if (symbol == "+" && userInput == (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "+" && userInput !== (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else if (symbol == "-" && userInput == (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "-" && userInput !== (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else {
alert("Something wrong happened. Try again.");
}
return userInput;
}
(The HTML)
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/stylesheet.css" />
<script src="js/script.js"></script>
<title>Improve Your Math Skills!</title>
</head>
<body>
<center>
<button onclick="userAnswer()">PLAY NOW!</button>
<div id="bubble"></div>
<div id="feedback"></div>
<!-- <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> -->
</center>
</body>
</html>
Thank you
You can use an input tag instead of the prompt. Change the HTML just as in Dinesh's answer;
<div id="bubble"></div>
<div id="inp" style="display: none;">
<input type="text" id="ans"></input> <button id="subBtn">Submit</button>
</div>
<div id="feedback"></div>
Now, for the JavaScript, there a few things to consider. Firstly, you have
var number1 = function() {
var numb1 = Math.floor(Math.random() * 41) + 10;
return numb1;
}
var number2 = function() {
var numb2 = Math.floor(Math.random() * 41) + 10;
return numb2;
}
Both functions do exactly the same thing; you don't need two separate functions to get two separate random numbers. So, only one function will suffice.
var number = function() {
return Math.floor(Math.random() * 41) + 10;
};
Secondly, now we have two functions. userAnswer to post a new question when 'Play Now!' is clicked and, say, evalAnswer to evaluate the answer written in the input field when 'Submit' is clicked.
In userAnswer, you generate two new random numbers and figure out which operation will be conducted on them. At this point, you can simply evaluate the answer yourself and store it in a global variable. This makes things easier when you evaluate the answer, you only need to do a simple comparison.
Other than that, you update innerHTML for bubble and display the div inp.
In evalAnswer, you get the value from ans and compare it with the previously computed value of the current answer, and then accordingly update feedback.innerHTML.
Here's the code;
//variable to maintain the current answer
var curAns = 0;
//Here, I get all the DOMElements I will use
var playBtn = document.getElementById('playBtn');
var bubble = document.getElementById('bubble');
var inp = document.getElementById('inp');
var ans = document.getElementById('ans');
var subBtn = document.getElementById('subBtn');
var feedback = document.getElementById('feedback');
//I add the event listeners
//This is equivalent to using 'onclick'
//in the HTML, and doing it this way is only
//my personal preference
playBtn.addEventListener('click', function() {userAnswer();}, false);
subBtn.addEventListener('click', function() {evalAnswer();}, false);
//Function to get random number
var number = function() {
return Math.floor(Math.random() * 41) + 10;
};
//This function will be executed when 'Play Now!' is clicked.
var userAnswer = function() {
//Get two separate random numbers in
//numb1 and numb2
var numb1 = number();
var numb2 = number();
var symbol = '';
var randomSymbol = Math.random();
//Determine the operation to be used
//and compute the corresponding correct answer for the current
//question
if (randomSymbol > 0.5) {
symbol = "+";
curAns = numb1+numb2;
} else {
symbol = "-";
curAns = numb1-numb2;
}
//Add math question to bubble
bubble.innerHTML = 'What is ' + numb1 + ' ' + symbol + ' ' + numb2 + '?';
feedback.innerHTML = '';
//Make inp div visible
inp.style.display = 'block';
//Reset input value to ''
ans.value = '';
};
//This function will be executed when 'Submit' is clicked
var evalAnswer = function() {
//Simply compare input value with computed
//answer and update feedback
if(parseInt(ans.value) !== curAns) {
feedback.innerHTML = 'Wrong answer, try again!';
}
else {
feedback.innerHTML = 'You got it right, congratulations!';
}
};
Here's a working example.
Hope that helped!
What I understand from your question is that you need the same functionality in HTML itself rather than driven by JS in a prompt box, if so,the below additions to your code should help:
HTML adition:
<div id="bubble"></div>
<div id="check_ans_div" style="display:none;">
<input type="text" id="txt_answer" />
<input type="submit" value="Check Answer" onclick="checkanswer()" />
</div>
<div id="feedback"></div>
JS changes:
var number1 = function() {
var numbx = Math.floor(Math.random() * 41) + 10;
return numbx;
}
var number2 = function() {
var numby = Math.floor(Math.random() * 41) + 10;
return numby;
}
var numb1=0; var numb2=0;
var userAnswer = function() {
numb1 = number1();
numb2 = number2();
var randomSymbol = Math.random();
if (randomSymbol > 0.5) {
var symbol = "+";
} else {
var symbol = "-";
}
// add the math question in the html bubble
document.getElementById('bubble').innerHTML = numb1 + symbol + numb2;
if(document.getElementById('check_ans_div').style.display=='none')
document.getElementById('check_ans_div').style.display='block';
document.getElementById('txt_answer').value='';
}
function checkanswer(){
var userInput= document.getElementById('txt_answer').value;
if (symbol == "+" && userInput == (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "+" && userInput !== (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else if (symbol == "-" && userInput == (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "-" && userInput !== (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else {
alert("Something wrong happened. Try again.");
}
}

Categories