How to solve a linear equation with algebra.js? - javascript

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

Related

Can't add together two variables which store an offsetHeight

I'm trying to add two numbers together so I can use a CSS calc function to reduce the top margin of an element so it shows just the title and its top line text.
var roomInfoPanel = document.querySelector(".room-info");
var panelCapacityInfo = parseInt(document.querySelector(".room-info__capacity").offsetHeight);
var panelTitleRoom = parseInt(document.querySelector(".room-info__title").offsetHeight);
var panelCombinedHeights = panelCapacityInfo + panelTitleRoom;
if (panelTitleRoom && panelCapacityInfo) {
document.querySelector(".room-info").style.marginTop = "calc( -" + panelCombinedHeights + "-7vw + -20px)";
}
However, panelCombinedHeights always returns undefined :(
I don't think this is a scope issue.
The parseInt was added after looking at this article, but without this no good either.
What am I doing wrong?
Try to convert variables to numbers
var roomInfoPanel = document.querySelector(".room-info");
var panelCapacityInfo = parseInt(document.querySelector(".room-info__capacity").offsetHeight);
var panelTitleRoom = parseInt(document.querySelector(".room-info__title").offsetHeight);
// Convert variables to numbers
// Print what to summ
console.log(panelCapacityInfo, panelTitleRoom)
var panelCombinedHeights = Number(panelCapacityInfo) + Number(panelTitleRoom);
// Print summ
console.log(panelCombinedHeights)
if (panelTitleRoom && panelCapacityInfo) {
console.log("Style to be applied:", "calc( -" + panelCombinedHeights + "-7vw + -20px)");
document.querySelector(".room-info").style.marginTop = "calc( -" + panelCombinedHeights + "-7vw + -20px)";
}
.room-info {
height: 200px;
}
.room-info__capacity {
height: 100px;
}
.room-info__title {
height: 70px;
}
<div class="room-info">
<div class="room-info__capacity">
1
</div>
<div class="room-info__title">
2
</div>
</div>
The function offsetHeigth already returns a number, so you don't need the parseInt() here.
Are the values panelCapacityInfo and panelTitleRoom defined or not?
If they are undefined then the error is probably in the querySelector.
var roomInfoPanel = document.querySelector(".room-info");
var panelCapacityInfo = parseInt(document.querySelector(".room-info__capacity").offsetHeight);
var panelTitleRoom = parseInt(document.querySelector(".room-info__title").offsetHeight);
var panelCombinedHeights = parseInt(panelCapacityInfo) + parseInt(panelCapacityInfo)
if (panelTitleRoom && panelCapacityInfo) {
document.querySelector(".room-info").style.marginTop = "calc( -" + panelCombinedHeights + "-7vw + -20px)";
}

Changing linear-gradient with Javascript not working

I'm trying to change the linear gradient with JavaScript in my project. My problem is that after running the code nothing happens. If I try to use the linear-gradient string directly in my CSS class container, everything works fine but it doesn't work with changing it via JavaScript. Here's the code I'm trying to run:
function init() {
var Lohn = "undefined";
var Datum = "undefined";
var Pausenstueck = "undefined";
var Zakstueck = "undefined";
var Ueberstundenstueck = "undefined";
var StundeKoord = "undefined";
var Tagesdauer = "undefined";
let UebersichtTemplate = document.createElement("dd");
let UebersichtDD = document.getElementById("Uebersicht_Window_child");
UebersichtTemplate.innerHTML = "<span class='textRight'>" + Lohn + "</span><span class='text'>" + Datum + "</span>";
let a = document.importNode( UebersichtTemplate,true);
a.classList.add("percentage", "percentage-" + Math.round(StundeKoord*Tagesdauer));
let colorString = "linear-gradient(to right, #9c9e9f 0%,#9c9e9f " + Pausenstueck + Zakstueck + Ueberstundenstueck + " 100%);"
UebersichtDD.appendChild(a);
a.style.backgroundImage = '-webkit-linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%, #F53323 50%, #F53323 100%)';
}
document.addEventListener("DOMContentLoaded", init);
<body>
<div id="Uebersicht_Window_child"></div>
</body>
I already tried using double quotes instead of single quotes but it also doesn't work. leaving the "-webkit-" doesn't solve my problem either... I absolutely don't know the problem. Hope you guys could help me :)
Thank you!
There is one major issue: You never actually insert the dd element that you imported into the document:
From Document​.import​Node():
The Document object's importNode() method creates a copy of a Node or
DocumentFragment from another document, to be inserted into the
current document later.
(Emphasis mine)
There are a couple of other issues, mainly around code structure and style - but they may not be pertinent to the core question - but also syntax problems with creating the colorString that may have been contributing.
function init() {
var Lohn = "undefined";
var Datum = "undefined";
var StundeKoord = "undefined";
var Tagesdauer = "undefined";
// -----------------------------
var Pausenstueck = "#9c9e9f 50%";
var Zakstueck = "#F53323 50%";
var Ueberstundenstueck = "#F53323 100%";
let UebersichtTemplate = document.createElement("dd");
UebersichtTemplate.innerHTML = "<span class='textRight'>" + Lohn + "</span>" +
"<span class='text'>" + Datum + "</span>";
let a = document.importNode( UebersichtTemplate, true );
a.classList.add( "percentage", "percentage-" + Math.round(StundeKoord*Tagesdauer) );
a.style.backgroundImage = `-webkit-linear-gradient(top right, #9c9e9f 0%, ${Pausenstueck}, ${Zakstueck}, ${Ueberstundenstueck} )`;
// insert the imported node.
document.body.appendChild(a);
}
document.addEventListener("DOMContentLoaded", init);
<body>
<div id="Uebersicht_Window_child"></div>
</body>

How to delete elements created by CreateElement and AppendChild

[
// Calendar
var calendar = document.getElementById("calendar");
calendar.addEventListener("click",function(){
factbox.style.bottom = "70px";
factbox.style.transition = "0s";
calendar.style.transform = "rotateX(-50deg)";
calendar.style.transformOrigin = "bottom center";
var hotdogs = document.createElement("IMG");
hotdogs.src = "SVG/hotdog2.svg";
hotdogs.setAttribute = ("id", "hotdogs");
everywhere.parentNode.removeChild("hotdogs");
});
// Hotdog
var hotdog = document.getElementById("hotdog");
var everywhere = document.getElementById("everywhere");
var NumClick4 = 0;
hotdog.addEventListener("click",function(){
var hotdogs = document.createElement("IMG");
hotdogs.src = "SVG/hotdog2.svg";
hotdogs.setAttribute = ("id", "hotdogs");
everywhere.appendChild(hotdogs);
var x = Math.floor(( Math.random() * 450) + 800);
NumClick4++;
console.log(x + " " + NumClick4);
hotdogs.style.width = "200px";
hotdogs.style.left = x + "px";
if(NumClick4 == 1) {
factbox.style.bottom = "70px";
factbox.style.transition = "0s";
} else {
}
});
<div id="hotdog" class="">
<img src="SVG/hotdog2.svg" alt="hotdog">
</div>
<div id="everywhere"></div>
<div id="calendar">
<img src="SVG/calendar.svg" alt="calendar">
</div>
<div id="factbox">
</div>
enter image description here
Sorry if my code looks messy. So as shown on the image, I want the hotdogs on the sky, which were created by "CreateElement" and "AppendChild" method to disappear using "RemoveChild" method. For example, when I click other elements like "flag", I want the just the new "hotdogs" to disappear. I think I am not getting how it works. I would appreciate advice and tips.
Following line is wrong by 2 counts
everywhere.parentNode.removeChild("hotdogs");
You are trying to remove something which hasn't been added yet
You need to remove the Element rather than string
i.e.
everywhere.parentNode.removeChild(hotdogs);

Celsius to Fahrenheit conversion- 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;

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

Categories