I've been working on this little snippet:
var a;
var b;
var c;
function generateResult() {
// Custom variables
var a = parseInt(document.getElementById("firstNumber").value);
var b = document.getElementById("operator").value;
var c = parseInt(document.getElementById("secondNumber").value);
console.log(a);
console.log(b);
console.log(c);
var calc = function(a, b, c) {
var result;
if (b == "+") {
console.log("Now in sum");
result = a + c;
return result;
}
else if (b == "-") {
console.log("Now in sub");
result = a - c;
return result;
}
else if (b == "/") {
console.log("Now in div");
result = a / c;
return result;
}
else if (b == "*") {
console.log("Now in tim");
result = a * c;
return result;
}
}
document.getElementById("result").innerHTML = (calc(a, b, c));
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test</title>
</head>
<body>
<form>
<h1>Calculator (basic)</h1><br><br>
First input:<br>
<input type="number" id="firstNumber"><br><br>
<select id="operator">
<option id="sum" value="+">+</option>
<option id="sub" value="-">-</option>
<option id="div" value="/">/</option>
<option id="tim" value="*">*</option>
</select><br><br>
Second input:<br>
<input type="number" id="secondNumber"><br><br>
</form>
<button onclick="generateResult()">=</button><br><br>
<h3 id="result"></h3>
</body>
<script src="script.js" defer></script>
</html>
I want this code to be modular so it can be implemented by everyone. Like this: http://semester4.nl/bounce/demo/
I've been working on learning some basic javascript. Someone suggested to me that I should try and write my code modular (even simple stuff like this). I've used this tutorial: https://www.youtube.com/watch?v=pOfwp6VlnlM No luck so far, can somebody help me out?
Thanks!
You can wrap this code in IIFE.
(() => {
// your code
})();
If you have many files, good idea will be use Webpack, that help you with work, with AMD or CommonJS.
Other option is use ES Modules, that should work without Webpack.