Find Roots and Logs - Instant Number Operations using JavaScript
Let's start with a working Tool first. You can enter a Value in the Number Field for instant calculation of the Square, Cube, Square Root, Cube Root, Log, Log2 and Log10 of the Number. All in one Calculation!
If you have noticed, as soon as you start writing a number in the Input field, the values start calculating. How does that Happen? Its the magic of JavaScript!
Try out the Tool below:
Number | |
Square | |
Cube | |
Square Root | |
Cube Root | |
Log | |
Log 2 | |
Log 10 |
Now, do you want to create a tool like this of your own? Great!
We've utilized very simple mathematical functions supported by JavaScript and a custom function to call these.
<input id="inputNumber" onchange="rootsAndLogs(this.value)" oninput="rootsAndLogs(this.value)" type="number" />
If you noticed, onchange and oninput are calling the function and we are passing the value of the input field to the function. Any change or input will instantly call the function we have written.
Check out the function below:
/** * Function to calculate Roots and Logs and update back to display * @author computengine.com */ function rootsAndLogs(valNum) { valNum = parseFloat(valNum); var sqrNum = document.getElementById("sqr"); var cubeNum = document.getElementById("cube"); var sqrtNum = document.getElementById("sqrt"); var cbrtNum = document.getElementById("cbrt"); var logNum = document.getElementById("log"); var log2Num = document.getElementById("log2"); var log10Num = document.getElementById("log10"); sqrNum.value = Math.pow(valNum,2); cubeNum.value = Math.pow(valNum,3); sqrtNum.value = Math.sqrt(valNum); cbrtNum.value = Math.cbrt(valNum); logNum.value = Math.log(valNum); log2Num.value = Math.log2(valNum); log10Num.value = Math.log10(valNum); }
What are we doing here? We are assigning a variable to each element which we have given an ID in the input box. And then, we'll update the value of the variable as per the calculation.
Math.pow, Math.sqrt, Math.cbrt, Math.log, Math.log2 and Math.log10 are all inbuilt functions of JavaScript. You can directly call them for your own calculations.
And because we are calling our custom function on onchange and onintput events, any update we make to the Input field will call all these functions and instantly update all the calculations. Cool isn't it!
Go Ahead, build your own cool tools webpage with the small little JavaScript and HTML trick we just showed you!
Comments
Post a Comment