1
\$\begingroup\$

I am writing a JavaScript calculator as a Freecodecamp frontend project. Here are mine .html and .js files. Your help or advices are welcome. Task objective: Build a CodePen.io app that is functionally similar to this.

Fulfill the below user stories. Use whichever libraries or APIs you need. Give it your own personal style.

User Story: I can add, subtract, multiply and divide two numbers.

User Story: I can clear the input field with a clear button.

User Story: I can keep chaining mathematical operations together until I hit the equal button, and the calculator will tell me the correct output.

Remember to use Read-Search-Ask if you get stuck.

When you are finished, click the "I've completed this challenge" button and include a link to your CodePen.

You can get feedback on your project by sharing it with your friends on Facebook.

<div class="container" align=center>
  <div class="col-sm-4 col-sm-offset-4 well">
    <p class="title">JAVASCRIPT CALCULATOR</p>
    <table >
      <tr height=60 class="screen-row">
        <td><h1 id="demo" class="screen-content">0</h1></td>
      </tr>
      <tr height=20 class="screen-row">
        <td><p id="demo2" class="screen-content">0</p></td>
      </tr>
    </table>
    <table>
      <tr height=30>
        <td><button onclick="key7()">7</button></td>
        <td><button onclick="key8()">8</button></td>
        <td><button onclick="key9()">9</button></td>
        <td><button onclick="funcDiv()">/</button></td>
      </tr>
      <tr height=30>
        <td><button onclick="key4()">4</button></td>
        <td><button onclick="key5()">5</button></td>
        <td><button onclick="key6()">6</button></td>
        <td><button onclick="funcMultiply()">x</button></td>
      </tr>
      <tr height=30>
        <td><button onclick="key1()">1</button></td>
        <td><button onclick="key2()">2</button></td>
        <td><button onclick="key3()">3</button></td>
        <td><button onclick="funcSub()">-</button></td>
      </tr>
      <tr height=30>
        <td colspan="2"><button onclick="key0()">0</button></td>
        <td><button onclick="funcDot()">,</button></td>
        <td><button onclick="funcAdd()">+</button></td>
      </tr>
      <tr height=30>
        <td colspan="2"><button onclick="funcClear()">clear</button></td>
        <td colspan="2"><button onclick="funcTotal()">=</button></td>
      </tr>
    </table>
  </div>
</div>

The javascript part:

var number = "",
    temp = "",
    total = 0,
    arr = [],
    arrShow = [],
    arrTemp = [],
    dotOn = false;;

function funcClear() {
    number = "";
    temp = "";
    arr = [];
    dotOn = false;
    arrShow = [];
    arrTemp = [];
    document.getElementById("demo").innerHTML = 0;
    document.getElementById("demo2").innerHTML = 0;
}
function funcReset() {
    setTimeout(function(){ funcClear(); }, 3000);
}
function funcTotal() {
    if (number) {
        arr.push(number);
        arrShow.push(number);
        number = "";
    } else {
        arr.pop();
    }

    total = arr.splice(0,1);

    while (arr.length > 0) {
        arrTemp = arr.splice(0, 2);
        if (arrTemp[0] == '-') {total = (1*total) - (1*arrTemp[1]);}
        if (arrTemp[0] == '+') {total = (1*total) + (1*arrTemp[1]);}
        if (arrTemp[0] == '/') {total = (1*total) / (1*arrTemp[1]);}
        if (arrTemp[0] == '*') {total = (1*total) * (1*arrTemp[1]);}
        total = (Math.round(total * 100) / 100);
        var totalStr = total.toString();
        if (totalStr.length < 12) {
            document.getElementById("demo").innerHTML = total;
            document.getElementById("demo2").innerHTML = arrShow.join(' ');
        } else {
            document.getElementById("demo").innerHTML = "Too big number";
            document.getElementById("demo2").innerHTML = "Resetting in 3 seconds...";
            funcReset();
        }
    }
    number = (Math.round(total * 100) / 100);
    temp = "";
    arr = [];
    dotOn = false;
    arrShow = [];
    arrTemp = [];
}
function funcSub() {
    if (number) {
        arr.push(number);
        arr.push('-');
        arrShow.push(number);
        arrShow.push('-');
        temp = number;
        number = "";
        dotOn = false;
        document.getElementById("demo").innerHTML = "-";
        document.getElementById("demo2").innerHTML = arrShow.join(' ');
    }
}
function funcAdd() {
    if (number) {
        arr.push(number);
        arr.push('+');
        arrShow.push(number);
        arrShow.push('+');
        temp = number;
        number = "";
        dotOn = false;
        document.getElementById("demo").innerHTML = "+";
        document.getElementById("demo2").innerHTML = arrShow.join(' ');
    }
}
function funcDiv() {
    if (number) {
        arr.push(number);
        arr.push('/');
        arrShow.push(number);
        arrShow.push('/');
        temp = number;
        number = "";
        dotOn = false;
        document.getElementById("demo").innerHTML = "/";
        document.getElementById("demo2").innerHTML = arrShow.join(' ');
    }
}
function funcMultiply() {
    if (number) {
        arr.push(number);
        arr.push('*');
        arrShow.push(number);
        arrShow.push('*');
        temp = number;
        number = "";
        dotOn = false;
        document.getElementById("demo").innerHTML = "*";
        document.getElementById("demo2").innerHTML = arrShow.join(' ');
    }
}
function funcDot() {
    if (number) {
        if (!dotOn) {
            dotOn = true;
            number = number.concat(".");
            document.getElementById("demo").innerHTML = number;
            if (arrShow.length > 0) {
                document.getElementById("demo2").innerHTML = arrShow.join(' ');
            } else {
                document.getElementById("demo2").innerHTML = 0;
            }
        }
    }
}
function key0() {
    if (number.length < 8) {
        number = number.concat("0");
        document.getElementById("demo").innerHTML = number;
        if (arrShow.length > 0) {
            document.getElementById("demo2").innerHTML = arrShow.join(' ');
        } else {
            document.getElementById("demo2").innerHTML = 0;
        }
    } else {
        document.getElementById("demo2").innerHTML = "Number limit reached";
    }
}
function key1() {
    if (number.length < 8) {
        number = number.concat("1");
        document.getElementById("demo").innerHTML = number;
        if (arrShow.length > 0) {
            document.getElementById("demo2").innerHTML = arrShow.join(' ');
        } else {
            document.getElementById("demo2").innerHTML = 0;
        }
    } else {
        document.getElementById("demo2").innerHTML = "Number limit reached";
    }
}
function key2() {
    if (number.length < 8) {
        number = number.concat("2");
        document.getElementById("demo").innerHTML = number;
        if (arrShow.length > 0) {
            document.getElementById("demo2").innerHTML = arrShow.join(' ');
        } else {
            document.getElementById("demo2").innerHTML = 0;
        }
    } else {
        document.getElementById("demo2").innerHTML = "Number limit reached";
    }
}
function key3() {
    if (number.length < 8) {
        number = number.concat("3");
        document.getElementById("demo").innerHTML = number;
        if (arrShow.length > 0) {
            document.getElementById("demo2").innerHTML = arrShow.join(' ');
        } else {
            document.getElementById("demo2").innerHTML = 0;
        }
    } else {
        document.getElementById("demo2").innerHTML = "Number limit reached";
    }
}
function key4() {
    if (number.length < 8) {
        number = number.concat("4");
        document.getElementById("demo").innerHTML = number;
        if (arrShow.length > 0) {
            document.getElementById("demo2").innerHTML = arrShow.join(' ');
        } else {
            document.getElementById("demo2").innerHTML = 0;
        }
    } else {
        document.getElementById("demo2").innerHTML = "Number limit reached";
    }
}
function key5() {
    if (number.length < 8) {
        number = number.concat("5");
        document.getElementById("demo").innerHTML = number;
        if (arrShow.length > 0) {
            document.getElementById("demo2").innerHTML = arrShow.join(' ');
        } else {
            document.getElementById("demo2").innerHTML = 0;
        }
    } else {
        document.getElementById("demo2").innerHTML = "Number limit reached";
    }
}
function key6() {
    if (number.length < 8) {
        number = number.concat("6");
        document.getElementById("demo").innerHTML = number;
        if (arrShow.length > 0) {
            document.getElementById("demo2").innerHTML = arrShow.join(' ');
        } else {
            document.getElementById("demo2").innerHTML = 0;
        }
    } else {
        document.getElementById("demo2").innerHTML = "Number limit reached";
    }
}
function key7() {
    if (number.length < 8) {
        number = number.concat("7");
        document.getElementById("demo").innerHTML = number;
        if (arrShow.length > 0) {
            document.getElementById("demo2").innerHTML = arrShow.join(' ');
          } else {
              document.getElementById("demo2").innerHTML = 0;
          }
    } else {
        document.getElementById("demo2").innerHTML = "Number limit reached";
    }
}
function key8() {
    if (number.length < 8) {
        number = number.concat("8");
        document.getElementById("demo").innerHTML = number;
        if (arrShow.length > 0) {
            document.getElementById("demo2").innerHTML = arrShow.join(' ');
          } else {
              document.getElementById("demo2").innerHTML = 0;
        }
    } else {
        document.getElementById("demo2").innerHTML = "Number limit reached";
    }
}
function key9() {
    if (number.length < 8) {
        number = number.concat("9");
        document.getElementById("demo").innerHTML = number;
        if (arrShow.length > 0) {
            document.getElementById("demo2").innerHTML = arrShow.join(' ');
        } else {
            document.getElementById("demo2").innerHTML = 0;
        }
    } else {
        document.getElementById("demo2").innerHTML = "Number limit reached";
    }
}
\$\endgroup\$
2
\$\begingroup\$

As there are many elements with similar logic you can use this approach:

var number = "",
  total = 0,
  regexp = /[0-9]/,
  mainScreen = document.getElementById("mainScreen");

function InputSymbol(num) {
  var cur = document.getElementById(num).value;
  var prev = number.slice(-1);
  // Do not allow 2 math operators in row
  if (!regexp.test(prev) && !regexp.test(cur)) {
    console.log("Two math operators not allowed after each other ;)");
    return;
  }
  number = number.concat(cur);
  mainScreen.innerHTML = number;
}

function CalculateTotal() {
  // Time for some EVAL magic
  total = (Math.round(eval(number) * 100) / 100);
  mainScreen.innerHTML = total;
}

function DeleteLastSymbol() {
  if (number) {
    number = number.slice(0, -1);
    mainScreen.innerHTML = number;
  }
  if (number.length === 0) {
    mainScreen.innerHTML = "0";
  }
}

function ClearScreen() {
  number = "";
  mainScreen.innerHTML = 0;
}
body, div, header, h1, p, table, tr, td {
    margin: 0px;
    padding: 0px;
}

header {
    letter-spacing: 6px;
    font-size: 14px;
}

table {
    width: 100%;
}

button {
    width: 100%;
    height: 50px;
    font-size: 18px;
}

.container {
    margin-top: 100px;
    margin-left: 100px;
    padding: 10px;
    font-family: 'Roboto', sans-serif;
    text-align: center;
    max-width: 400px;
    background-color: silver;
    border: 1px solid black;
    border-radius: 5px;
}

.screen {
    margin-top: 10px;
    margin-bottom: 10px;
    padding: 10px;
    background-color: #2d2929;
    color: white;
    text-align: right;
    font-family: 'Prompt', sans-serif;
}
<html>

<body>
  <div class="container">
    <header>JAVASCRIPT CALCULATOR</header>
    <div class="screen">
      <h1 id="mainScreen">0</h1>
    </div>
    <table>
      <tr>
        <td><button value="7" id="7" onclick="InputSymbol(7)">7</button></td>
        <td><button value="8" id="8" onclick="InputSymbol(8)">8</button></td>
        <td><button value="9" id="9" onclick="InputSymbol(9)">9</button></td>
        <td><button onclick="DeleteLastSymbol()">c</button></td>
      </tr>
      <tr>
        <td><button value="4" id="4" onclick="InputSymbol(4)">4</button></td>
        <td><button value="5" id="5" onclick="InputSymbol(5)">5</button></td>
        <td><button value="6" id="6" onclick="InputSymbol(6)">6</button></td>
        <td><button value="/" id="104" onclick="InputSymbol(104)">/</button></td>
      </tr>
      <tr>
        <td><button value="1" id="1" onclick="InputSymbol(1)">1</button></td>
        <td><button value="2" id="2" onclick="InputSymbol(2)">2</button></td>
        <td><button value="3" id="3" onclick="InputSymbol(3)">3</button></td>
        <td><button value="*" id="103" onclick="InputSymbol(103)">*</button></td>
      </tr>
      <tr>
        <td colspan="2"><button value="0" id="0" onclick="InputSymbol(0)">0</button></td>
        <td><button value="-" id="102" onclick="InputSymbol(102)">-</button></td>
        <td><button value="+" id="101" onclick="InputSymbol(101)">+</button></td>
      </tr>
      <tr>
        <td colspan="2"><button onclick="ClearScreen()">clear</button></td>
        <td colspan="2"><button onclick="CalculateTotal()">=</button></td>
      </tr>
    </table>
  </div>
</body>

</html>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.