My mini calculator isn't working. Please read description - javascript

I am trying to make a calculator in javascript and it is not working. When I try to do, say 1 + 1 it gives me 11 and this is the same for all the numbers here is my code:
var slider1 = document.getElementById("myRange1");
var slider2 = document.getElementById("myRange2");
var output = document.getElementById("output");
var fullEquat = document.getElementById("equation");
var add1 = slider1.value;
var add2 = slider2.value;
output.innerHTML = slider1.value; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
slider1.oninput = function() {
output.innerHTML = this.value;
}
slider2.oninput = function() {
add1 = slider1.value;
add2 = slider2.value;
equals = add1 + add2;
fullEquat.innerHTML = slider1.value + "+" + slider2.value + "=" + equals;
}
slider1.oninput = function() {
add1 = slider1.value;
add2 = slider2.value;
equals = add1 + add2;
fullEquat.innerHTML = slider1.value + "+" + slider2.value + "=" + equals;
}
.slider {
width: 400px;
display: inline;
}
.equal {
text-align: center;
font-size: 100pt;
margin: 0 0 0 0;
}
<div class="slidecontainer">
<input type="range" min="0" max="1000" value="500" class="slider" id="myRange1">
+
<input type="range" min="0" max="1000" value="500" class="slider" id="myRange2">
</div>
<p class="equal">=</p>
<p id="output" class="output"></p>
<p id="equation" class="equat"> + = </p>

When you declared add1 = slider1.value; add2 = slider2.value; you got a string instead of a number... you should put them inside a Number() like this
add1 = Number(slider1.value);
add2 = Number(slider2.value);

Value property returns you a string, you can use a simple trick to multiply it with 1 like add1 = slider. value * 1. and it will give you a number

.value property return a string
you have to use .valueAsNumber to get a number
sample code:
const calcForm = document.forms['form-calculation']
, pOutput = document.getElementById('p-output')
;
calcForm.oninput=_=>
{
calcForm['range-1'].nextElementSibling.textContent = calcForm['range-1'].value
calcForm['range-2'].nextElementSibling.textContent = calcForm['range-2'].value
pOutput.textContent = calcForm['range-1'].valueAsNumber
+ calcForm['range-2'].valueAsNumber
}
form { width: 20em; }
input[type="range"] {width: 80%; }
label { font-size:2em; font-weight: bold; text-align: center; display: block; width: 80%;}
<form name="form-calculation">
<input type="range" min="0" max="1000" value="500" name="range-1"><span>500</span>
<label>+</label>
<input type="range" min="0" max="1000" value="500" name="range-2"><span>500</span>
<label>=</label>
</form>
<p id="p-output" class="output">1000</p>

Related

How to add multiple shadow layers of boxShadow with Javascript

I try to build a boxShadow generator, where the user can add multiple layers of boxShadow. Anything like the example below:
box-shadow: rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, rgba(0, 0, 0, 0.3) 0px 8px 16px -8px;
What I have so far:
A constructor function, which creates my shadows.
function Shadow(paramId) {
this.shadowId = paramId;
this.horizontalValue = 'horizontalRange' + paramId;
this.verticalValue = 'verticalRange' + paramId;
this.blurValue = 'blurRange' + paramId;
this.spreadValue = 'spreadRange' + paramId;
this.colorValue = 'colorInput' + paramId;
}
...and a function, which gets the value of the sliders:
function getRangeValue () {
const shadowBox = document.getElementById('shadowBox');
let shadowId = this.id.slice(this.id.length - 1, this.id.length) - 1; // my Id's are like xOffset1
let xValue = document.getElementById(shadowObjContainer[shadowId].horizontalValue).value;
let yValue = document.getElementById(shadowObjContainer[shadowId].verticalValue).value;
let blurValue = document.getElementById(shadowObjContainer[shadowId].blurValue).value;
let spreadValue = document.getElementById(shadowObjContainer[shadowId].spreadValue).value;
let colorValue = document.getElementById(shadowObjContainer[shadowId].colorValue).value;
shadowParam = `${xValue}px ${yValue}px ${blurValue}px ${spreadValue}px ${colorValue}`;
shadowBox.style.boxShadow = shadowParam;
}
It does work, that my sliders do what they are supposed to do. But I don't know, how to create another shadow parameter (", " + shadowParam).
Hopefully someone can help me.
Thank you :)
A working example to work on was helpful. I hypothesized your environment and this is my commented idea.
// The class with all controls for each shadows
let Control = class {
constructor(paramId) {
this.shadowId = paramId;
this.horizontalValue = 'horizontalRange' + paramId;
this.verticalValue = 'verticalRange' + paramId;
this.blurValue = 'blurRange' + paramId;
this.spreadValue = 'spreadRange' + paramId;
this.colorValue = 'colorInput' + paramId;
}
}
// Generates the shadow for each initialized Control class
function getRangeValue() {
const shadowBox = document.getElementById('shadowBox');
let shadowParam = '';
for (let i = 0; i < Controls.length; i++) {
let shadowId = Controls[i].shadowId;
let xValue = document.getElementById(Controls[i].horizontalValue).value;
let yValue = document.getElementById(Controls[i].verticalValue).value;
let blurValue = document.getElementById(Controls[i].blurValue).value;
let spreadValue = document.getElementById(Controls[i].spreadValue).value;
let colorValue = document.getElementById(Controls[i].colorValue).value;
shadowParam = (shadowParam == '' ? '' : shadowParam + ', ') + `${xValue}px ${yValue}px ${blurValue}px ${spreadValue}px ${colorValue}`;
}
shadowBox.style.boxShadow = shadowParam;
}
// Initialization of the Control classes based on the "group" of controls named "ShadowControls"
let ShadowControlsEl = document.getElementsByClassName("ShadowControls");
let Controls = Array();
for (let i = 0; i < ShadowControlsEl.length; i++) {
Controls.push(new Control(i + 1));
}
// Generate the first Shadows
getRangeValue();
// Initialize listeners for values change
let AllControls = document.getElementsByClassName('listener');
for (let i = 0; i < AllControls.length; i++) {
AllControls[i].addEventListener('change', getRangeValue);
}
#shadowBox {
width: 100px;
height: 100px;
margin: 50px;
background-color:#ff00ff;
}
<div class="ShadowControls">
<input id="horizontalRange1" class="listener" type="range" min="-100" max="100" value="10">
<input id="verticalRange1" class="listener" type="range" min="-100" max="100" value="10">
<input id="blurRange1" class="listener" type="range" min="0" max="100" value="0">
<input id="spreadRange1" class="listener" type="range" min="0" max="100" value="0">
<input id="colorInput1" class="listener" type="color" value="#FF0000">
</div>
<hr>
<div class="ShadowControls">
<input id="horizontalRange2" class="listener" type="range" min="-100" max="100" value="-10">
<input id="verticalRange2" class="listener" type="range" min="-100" max="100" value="-10">
<input id="blurRange2" class="listener" type="range" min="0" max="100" value="0">
<input id="spreadRange2" class="listener" type="range" min="0" max="100" value="0">
<input id="colorInput2" class="listener" type="color" value="#FFFF00">
</div>
<div id="shadowBox">
Shadow here
</div>

How to display the slider value in html?

I have been recently working on a project which demonstrates the use of the arithmetic sequence. The user will use a slider to input the value for the starting term, which is t0; the difference, which is d; the number of terms, which is represented as n. However, I could not get the code to work. I used the solution in this post: HTML5 input type range show range value . A demo of my code down below:
var t0, difference, boxedNums, numOfTerms, redCircle, redTriangle, redRectangle, blueCircle, blueTriangle, blueRectangle;
function genTn() {
reset();
t0 = document.getElementById("t0").value;
difference = document.getElementById("d").value;
numOfTerms = document.getElementById("tn").value;
var tn;
document.getElementById('buildButton').style.display = 'none';
for (n = 0; n < numOfTerms; n++) {
tn = t0 * 1 + difference * n;
setTimeout(buildNextOne, 3000 * n, n, tn);
}
setTimeout(showButton, 3000 * numOfTerms);
document.getElementById("formulat0").innerHTML = t0;
document.getElementById("formulad").innerHTML = difference;
document.getElementById("formulan").innerHTML = numOfTerms;
}
function buildNextOne(n, tn) {
var insert = '<div class="col-sm-4 col-md-2 boxed center">'
insert += 't<sub>' + n + '</sub><br>'
insert += '<span class="tn">' + tn + '</span><br>'
insert += getPicsRepresentOfNumber(tn);
insert += '</div>'
document.getElementById("boxArea").innerHTML += insert;
var msg = new SpeechSynthesisUtterance(tn);
window.speechSynthesis.speak(msg);
}
function showButton() {
document.getElementById('buildButton').style.display = '';
}
function reset() {
document.getElementById("boxArea").innerHTML = "";
}
function getPicsRepresentOfNumber(number) {
var totalHund = 0,
totalTens = 0,
totalOnes = 0,
returnHtml = '';
totalHund = Math.abs(parseInt(number / 100));
var diffAfterRemovingHund = number % 100;
totalTens = Math.abs(parseInt(diffAfterRemovingHund / 10));
totalOnes = Math.abs(parseInt(diffAfterRemovingHund % 10));
for (var i = 0; i < totalHund; i++) {
returnHtml += number < 0 ? "<img src='imgs/negativeHundred.png'>&nbsp" : "<img src='imgs/hundred.png'>&nbsp";
if (i == 4) {
returnHtml += "&nbsp"
}
}
returnHtml += "<br>";
for (var i = 0; i < totalTens; i++) {
returnHtml += number < 0 ? "<img src='imgs/negativeTen.png'>&nbsp" : "<img src='imgs/ten.png'>&nbsp";
if (i == 4) {
returnHtml += "&nbsp";
}
}
returnHtml += "<br>";
for (var i = 0; i < totalOnes; i++) {
returnHtml += number < 0 ? "<img src='imgs/negativeOne.png'>&nbsp" : "<img src='imgs/one.png'>&nbsp";
if (i == 4) {
returnHtml += "&nbsp";
}
}
returnHtml += "<br>";
return returnHtml;
}
function updateT0Input(t0) {
document.getElementById("updatet0").value = t0;
}
function updateDInput(difference) {
document.getElementById("updated").value = difference;
}
function updateNInput(numOfTerms) {
document.getElementById("updaten").value = numOfTerms;
}
.center {
text-align: center;
}
#equation {
background-color: lightgreen;
text-align: center;
border-radius: 10%;
}
body {
background-color: lightblue;
}
#formula {
background-color: lightgreen;
}
.boxed {
border: 1px solid gray;
margin-top: 10px;
background-color: beige;
}
.tn {
font-size: 3em;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Assignment 10a2</title>
</head>
<body>
<div id="formula">
Formula: <br>
t<sub>n</sub> = <span id="formulat0">t<sub>0</sub></span> + <span id="formulad">d</span>*<span id='formulan'>n</span> <br>
<br>
t<sub>0</sub> = <span id="updatet0"></span>
<input type="range" min="-50" max="50" value="0" id="t0" class="slider" onchange="updateT0Input(this.value);">
<br>
d = <span id="updated"></span>
<input type="range" min="-50" max="50" value="0" id="d" class="slider" onchange="updateDInput(this.value);">
<br>
n = <span id="updaten"></span>
<input type="range" min="1" max="20" value="10" id="tn" class="slider" onchange="updateNInput(this.value);">
<br>
<button id="buildButton" style="display:''" type="button" class="btn btn-warning"
onclick="genTn()">Generate</button>
</div>
<br>
<div class="container">
<div class="row" id="boxArea">
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"
integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"
integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k"
crossorigin="anonymous"></script>
<script src="10a2.js"></script>
</body>
I added the functions updateT0Input, updateDInput, and updateNInput:
function updateT0Input(t0) {
document.getElementById("updatet0").value = t0;
}
function updateDInput(difference) {
document.getElementById("updated").value = difference;
}
function updateNInput(numOfTerms) {
document.getElementById("updaten").value = numOfTerms;
}
And my html slidebars are here:
t<sub>0</sub> = <span id="updatet0"></span>
<input type="range" min="-50" max="50" value="0" id="t0" class="slider" onchange="updateT0Input(this.value);">
<br>
d = <span id="updated"></span>
<input type="range" min="-50" max="50" value="0" id="d" class="slider" onchange="updateDInput(this.value);">
<br>
n = <span id="updaten"></span>
<input type="range" min="1" max="20" value="10" id="tn" class="slider" onchange="updateNInput(this.value);">
Did I do something wrong?
Please do not mind the undisplayable images in the demo
JSFiddle with your code snippet: https://jsfiddle.net/u92ws7ce/1/
Here's your HTML with slightly modified class names:
t<sub>0</sub> = <span id="updatet0"></span>
<input type="range" min="-50" max="50" value="0" id="t0" class="slider1" onchange="updateT0Input(this.value);">
<p>Value: <span id="demo1"></span></p>
<br>
d = <span id="updated"></span>
<input type="range" min="-50" max="50" value="0" id="d" class="slider2" onchange="updateDInput(this.value);">
<p>Value: <span id="demo2"></span></p>
<br>
n = <span id="updaten"></span>
<input type="range" min="1" max="20" value="10" id="tn" class="slider3" onchange="updateNInput(this.value);">
<p>Value: <span id="demo3"></span></p>
And add this to your JS file:
var output1 = document.getElementById("demo1");
output1.innerHTML = slider1.value;
slider1.oninput = function() {
output1.innerHTML = this.value;
}
var slider2 = document.getElementById("d");
var output2 = document.getElementById("demo2");
output2.innerHTML = slider2.value;
slider2.oninput = function() {
output2.innerHTML = this.value;
}
var slider3 = document.getElementById("tn");
var output3 = document.getElementById("demo3");
output3.innerHTML = slider3.value;
slider3.oninput = function() {
output3.innerHTML = this.value;
}
Make sure you identify each slider with a unique class name and id. You'll want to refactor it to be programmatic and use functions to encapsulate repetitive logic.
Reference: https://www.w3schools.com/howto/howto_js_rangeslider.asp

Simple Javascript Loop Using input box variable

I'm just trying to start with JavaScript and have put this little loop together. Providing I put 1 in the start box.. it works fine. If I put anything else though the loop itself never takes place.
According to the console my variables should all match the criteria for the loop to activate so I don't see the problem
function myFunction() {
console.clear();
var Start = document.getElementById("Start").value
console.log("Start=", Start)
var End = document.getElementById("End").value
console.log("End=", End)
var which_one = document.getElementById("which_one").value
console.log("which_one=", which_one)
var i = Start;
console.log("i=", i);
var Counter_Array = "";
console.log("Counter Array =", Counter_Array);
var Counter_Array_Split = "";
console.log("Counter Array Split = ", Counter_Array_Split)
var Show_Me = "";
console.log("Show Me = ", Show_Me)
console.log("------Loop Starts------")
for (; Start < End; Start++) {
console.log("Start=", Start)
console.log("i looped=", Start);
Counter_Array += "," + Start
var Counter_Array_Split = Counter_Array.split(',');
console.log("CounterArrayLog=", Counter_Array);
console.log("Counter Array Split = ", Counter_Array_Split);
// sets all elements with the id demo to have the value of the newURL variable
document.getElementById("array").innerHTML = Counter_Array_Split;
}
console.log("------Loop Ends------")
var Show_Me = Counter_Array_Split[which_one]
console.log("Show Me = ", Show_Me)
document.getElementById("my_val").innerHTML = Show_Me;
}
.My_Form {
display: block;
background-color: orange;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
.my_div {
display: block;
background-color: lightblue;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
<h2>Example Javascript Loop</h2>
<div class="My_Form">
Start #: <input type="text" name="Start" id="Start" value="2"><br> End #: <input type="text" name="fname" id="End" value="10"> <br> Show
me the <input type="text" name="fname" id="which_one" value="5">th value in the array <br>
</div>
<br>
<div class="my_div">
The array built was
<p id="array"></p>
The Value picked was
<p id="my_val"></p>
</div><br>
<button onclick="myFunction()">
Click Me
</button>
<br>
You need to use integers in the for loop, by default you use string, so you need to parse it first.
1st problem: '5' < '10' this is false.
2nd problem: '5'++ will convert it to 5 and only after that will be incremented.
function myFunction() {
console.clear();
var Start = parseInt( document.getElementById("Start").value, 10)
console.log("Start=", Start)
var End = parseInt(document.getElementById("End").value, 10)
console.log("End=", End)
var which_one = document.getElementById("which_one").value
console.log("which_one=", which_one)
var i = Start;
console.log("i=", i);
var Counter_Array = "";
console.log("Counter Array =", Counter_Array);
var Counter_Array_Split = "";
console.log("Counter Array Split = ", Counter_Array_Split)
var Show_Me = "";
console.log("Show Me = ", Show_Me)
console.log("------Loop Starts------")
for (; Start < End; Start++) {
console.log("Start=", Start)
console.log("i looped=", Start);
Counter_Array += "," + Start
var Counter_Array_Split = Counter_Array.split(',');
console.log("CounterArrayLog=", Counter_Array);
console.log("Counter Array Split = ", Counter_Array_Split);
// sets all elements with the id demo to have the value of the newURL variable
document.getElementById("array").innerHTML = Counter_Array_Split;
}
console.log("------Loop Ends------")
var Show_Me = Counter_Array_Split[which_one]
console.log("Show Me = ", Show_Me)
document.getElementById("my_val").innerHTML = Show_Me;
}
.My_Form {
display: block;
background-color: orange;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
.my_div {
display: block;
background-color: lightblue;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
<h2>Example Javascript Loop</h2>
<div class="My_Form">
Start #: <input type="text" name="Start" id="Start" value="2"><br> End #: <input type="text" name="fname" id="End" value="10"> <br> Show
me the <input type="text" name="fname" id="which_one" value="5">th value in the array <br>
</div>
<br>
<div class="my_div">
The array built was
<p id="array"></p>
The Value picked was
<p id="my_val"></p>
</div><br>
<button onclick="myFunction()">
Click Me
</button>
<br>

Prevent slider from jumping when value is changed

I have a slider that live-updates the value on a label tag to the right of it. What should I do to prevent it from "jumping" when the value goes from 1-digit value to 2-digits value? How can I give the label a fixed position so that it won't change the layout:
var range = document.getElementById('range');
range.addEventListener('input', rangeChange);
function rangeChange() {
label.innerHTML = this.value;
}
<label id="label">0</label>
<input id="range" type="range" value=0 min=0 max=100>
Either add width: 20px;display: inline-block; to the label.
Or
Add a wrapper around both the elements and give them display: flex; align-items: center; style and width to the label.
var range = document.getElementById('range');
range.addEventListener('input', rangeChange);
function rangeChange() {
label.innerHTML = this.value;
}
<div style="display: flex; align-items: center;">
<label id="label" style="width: 20px;">0</label>
<input id="range" type="range" value=0 min=0 max=100>
</div>
Option 1: Put label to right side of slider
var range = document.getElementById('range');
range.addEventListener('input', rangeChange);
function rangeChange() {
label.innerHTML = this.value;
}
<input id="range" type="range" value=0 min=0 max=100>
<label id="label">0</label>
Option 2: Zero padding:
var range = document.getElementById('range');
range.addEventListener('input', rangeChange);
function rangeChange() {
var val = +(this.value);
if (10 > val) {
val = '00' + val;
} else if (100 > val) {
val = '0' + val;
}
label.innerHTML = val;
}
<label id="label">000</label>
<input id="range" type="range" value=0 min=0 max=100>

how to match more range sliders style to store in a single element by id

Hi I'm working on a project where I have four range sliders
every slider change a single css property of the html element (in particular a single webkit filter to everything)
I have:
hue
blur
grayscale
invert
now:
when I use a single slider it's all ok
but when i leave the slider and I use another one it set only one parameter to the style, writing over the previous
here an example of the code
HTML: this is one of the sliders
<section id="filters" class="clearfix">
<input type="range" data-default="0" value="0" min="0" max="360" step="1" id="hue-rotate" oninput="hueFunction(this.value)">
</section>
JS: these are the functions
//filters
//hue
function hueFunction(hueVal) {
var setAs = hueVal + "deg";
document.getElementById("html").setAttribute("style", "-webkit-filter:hue-rotate(" + setAs + ")");
}
//blur
function blurFunction(blurVal) {
var setAs = blurVal + "px";
document.getElementById("html").setAttribute("style", "-webkit-filter:blur(" + setAs + ")");
}
//grayscale
function grayscaleFunction(grayscaleVal) {
var setAs = grayscaleVal + "%";
document.getElementById("html").setAttribute("style", "-webkit-filter:grayscale(" + setAs + ")");
}
//invert
function invertFunction(invertVal) {
var setAs = invertVal + "%";
document.getElementById("html").setAttribute("style", "-webkit-filter:invert(" + setAs + ")");
}
I would like to use every sliders together
Check this.
//filters
//hue
function hueFunction(hueVal) {
apply_filter('hue-rotate', hueVal + 'deg');
}
//blur
function blurFunction(blurVal) {
apply_filter('blur', blurVal + 'px');
}
//grayscale
function grayscaleFunction(grayscaleVal) {
apply_filter('grayscale', grayscaleVal + '%');
}
//invert
function invertFunction(invertVal) {
apply_filter('invert', invertVal + '%');
}
var apply_filter = function (fil, val) {
var filter = document.getElementById('html').style.filter.trim().split(' ').filter(function (a) { return a.trim(); });
var f = false;
filter.forEach(function (v, i) {
if (v.indexOf(fil) === 0) {
filter[i] = fil + '(' + val + ')';
f = true;
}
});
if (f === false) filter.push(fil + '(' + val + ')');
document.getElementById('html').style.filter = filter.join(' ');
};
#filters > input {
display: block;
}
#html {
height: 80px;
width: 80px;
border: 1px solid #000;
background-color: #F00;
}
<section id="filters" class="clearfix">
<label for="hue-rotate">Hue</label>
<input type="range" data-default="0" value="0" min="0" max="360" step="1" id="hue-rotate" oninput="hueFunction(this.value)">
<label for="blur-rotate">Blur</label>
<input type="range" data-default="0" value="0" min="0" max="360" step="1" id="blur-rotate" oninput="blurFunction(this.value)">
<label for="gray-rotate">Grayscale</label>
<input type="range" data-default="0" value="0" min="0" max="360" step="1" id="gray-rotate" oninput="grayscaleFunction(this.value)">
<label for="invert-rotate">Invert</label>
<input type="range" data-default="0" value="0" min="0" max="360" step="1" id="invert-rotate" oninput="invertFunction(this.value)">
</section>
<div id="html"></div>

Categories

Resources