Question

In: Computer Science

Calculator in JavaScript. No use of switch statements or CSS. Project Standards: Students will use click...

Calculator in JavaScript. No use of switch statements or CSS.

Project Standards:

  • Students will use click events to capture user input.
  • Students will use variables to store information needed by their application and keep track of their program’s state.
  • Students will use conditionals to control project flow.

Project Task

You will be building a simple calculator in the browser. It should be able to add, subtract, divide, and multiply. Your program should do the following:

  1. Display a standard calculator to the user (you have starter files to help you with this).
  2. You will need to make references to all the proper HTML elements you'll be using to display elements to the user.
  3. You should make variables to keep track of the 1st number, operator, 2nd number, and the result of the math.
  4. When a user clicks on a button it should work like a standard calculator.
    1. Every number they click should be captured and build the 1st number until they click an operator (Ex. If they click 1 and 8, your program should display 18 to them)
    2. Clicking an operator (+, -, x, =) should only work if they have clicked numbers first.
    3. A user can only fill out the 2nd number once they have filled out the 1st number and clicked an operator.
    4. The = key will only work if a user has clicked both a 1st number, an operator, and a 2nd number. When they have filled in all the necessary inputs, = will display the proper number to them (Ex. if they input 5, +, and 7, they should be displayed 12).
    5. The clear button will clear all prior input and allow the user to start over.
  5. Your JavaScript code will form the conditional logic to determine whether a clicked button should work or not.
  6. You should display the 1st number, the operator, the 2nd number, and the math output (sum, product, difference, quotient) to the user at the appropriate times.

STARTER HTML CODE

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <title>Calculator Starter</title>

  <!-- Added a link to Bootstrap-->

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

</head>

<body>

  <div class="jumbotron">

    <h1 class="text-center">JavaScript Calculator</h1>

  </div>

  <div class="container">

    <div class="row">

      <!-- Calculator Card -->

      <div class="col-lg-4">

        <div class="card">

          <h3 class="card-header">Calculator</h3>

          <div class="card-body">

            <button id="button-1" class="btn btn-primary number" value="1">1</button>

            <button id="button-2" class="btn btn-primary number" value="2">2</button>

            <button id="button-3" class="btn btn-primary number" value="3">3</button>

            <button id="button-plus" class="btn btn-danger operator" value="plus">+</button>

            <br><br>

            <button id="button-4" class="btn btn-primary number" value="4">4</button>

            <button id="button-5" class="btn btn-primary number" value="5">5</button>

            <button id="button-6" class="btn btn-primary number" value="6">6</button>

            <button id="button-minus" class="btn btn-danger operator" value="minus">&minus;</button>

            <br><br>

            <button id="button-7" class="btn btn-primary number" value="7">7</button>

            <button id="button-8" class="btn btn-primary number" value="8">8</button>

            <button id="button-9" class="btn btn-primary number" value="9">9</button>

            <button id="button-multiply" class="btn btn-danger operator" value="times">&times;</button>

            <br><br>

            <button id="button-0" class="btn btn-primary number" value="0">0</button>

            <button id="button-divide" class="btn btn-danger operator" value="divide">&divide;</button>

            <button id="button-power" class="btn btn-danger operator" value="power">^</button>

            <button id="button-equal" class="btn btn-success equal" value="equals">=</button>

            <br><br>

            <button id="button-clear" class="btn btn-dark clear" value="clear">clear</button>

          </div>

        </div>

      </div>

      <!-- Result Card -->

      <div class="col-lg-6">

        <div class="card">

          <h3 class="card-header">Result</h3>

          <div class="card-body">

            <h1 id="first-number"></h1>

            <h1 id="operator"></h1>

            <h1 id="second-number"></h1>

            <hr>

            <h1 id="result"></h1>

          </div>

        </div>

      </div>

    </div>

  </div>

  <script src="main.js"></script>

</body>

</html>

STARTER JAVASCRIPT CODE

// BUTTONS ON THE PAGE

const numberButtons = document.querySelectorAll('.number');

const operatorButtons = document.querySelectorAll('.operator');

const equalButton = document.querySelector('.equal');

const clearButton = document.querySelector('.clear');

// TODO make references to all the proper HTML elements you'll be using to display elements to the user

// TODO make variables to keep track of the 1st number, operator, 2nd number, and the result of the math.

for(let i = 0; i < numberButtons.length; i++) {

  numberButtons[i].addEventListener('click', clickNumber);

}

for(let i = 0; i < operatorButtons.length; i++) {

  operatorButtons[i].addEventListener('click', clickOperator);

}

equalButton.addEventListener('click', clickEqualButton);

clearButton.addEventListener('click', clickClearButton);

function clickNumber(event) {

  console.log(event.target.value);

  // CODE GOES HERE

}

function clickOperator(event) {

  console.log(event.target.value);

  // CODE GOES HERE

}

function clickEqualButton() {

  // CODE GOES HERE

}

function clickClearButton() {

  // CODE GOES HERE

}

Solutions

Expert Solution

THE BELOW PROGRAMS FOLLOWS THE PROJECT STANDARDS FOR ABOVE STATEMENT:

style.css //CSS FILE

body,
html {
height: 100%;
padding: 0;
margin: 0;
}

body {
background-color: #e8dcd0;
font-family: 'Lato', Helvetica, Arial, sans-serif;
font-weight: 300;
font-size: 16px;
}

a {
outline: 0;
}

h1 {
font-size: 9vh;
color: #fff;
margin: 0;
}

.container-fluid {
padding: 0;
height: 100%;
position: relative;
}

#calculator {
height: 100%;
max-width: 100%;
background-color: #99dccb;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
background: -webkit-linear-gradient(#a9e8d8, #74beac); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(#a9e8d8, #74beac); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(#a9e8d8, #74beac); /* For Firefox 3.6 to 15 */
background: linear-gradient(#99dccb, #61af9d); /* Standard syntax */
}
#header {
padding: 0 10px;
height: 11%;
}
#display,
#history {
text-align: right;
padding: 0 5%;
overflow: hidden;
}

#display {
width: 100%;
background-color: #fff;
opacity: .85;
font-size: 13vh;
height: 18%;
}

#history {
width: 100%;
border-top: 2px solid #99dccb;
background-color: #fff;
opacity: .85;
font-size: 3.5vh;
height: 5%;
}

#keypad {
height: 61%;
}

.row {
margin: 0;
height: 20%;
}

.col-sm-3 {
width: 23%;
margin: 2px;
}

.key {
color: #fff;
height: 20%;
}

.btn {
font-size: 7vh;
}
#delete {
font-variant: small-caps;
font-size: 6vh;
}
#decimal {
font-size: 6rem;
line-height: 0;
}
footer {
font-size: 3vh;
height: 5%;
color: #fff;
}
footer a, footer a:active, footer a:hover {
color: #fff;
text-decoration: underline;
}

@media (min-width: 769px) {
#calculator {
width: 400px;
height: 720px;
margin-top: 75px;
border-radius: 10px;
}
h1 {
font-size: 3.5em;
padding-top: 6px;
}
#header {
border-radius: 10px;
}
#display {
font-size: 5em;
}
#history {
font-size: 1.3em;
}
.btn {
font-size: 2.2em;
}
#delete {
font-size: 2.4em;
}
footer {
font-size: 1.1em;
}
}

script.js //JAVASCRIPT FILE

$(document).ready(function () {

var calcStr = ""; // main display
var histStr = ""; // history display
var total = ""; // running total
var visible = false; //main display
var dpoint_active = true; // able to create decimal
var oper_active = true; // able to use operator

//get data when calculator key is clicked
document.getElementById('keypad').addEventListener('click', getKey);

function getKey(k) {
var key = k.target.id;
switch (key) {
case 'zero': key = 0;
break;
case 'one': key = 1;
break;
case 'two': key = 2;
break;
case 'three': key = 3;
break;
case 'four': key = 4;
break;
case 'five': key = 5;
break;
case 'six': key = 6;
break;
case 'seven': key = 7;
break;
case 'eight': key = 8;
break;
case 'nine': key = 9;
break;
}
compute(key);
}

//display and calulate
function displayIt(display, history) {
document.getElementById("display").innerHTML = display;
document.getElementById("history").innerHTML = history;
}

function calcIt(show, func) {
calcStr += show;
histStr += show;
total += func;
displayIt(calcStr, histStr);
}

function deleteOne() {
calcStr = calcStr.slice(0, -1);
histStr = histStr.slice(0, -1);
total = total.slice(0, -1);
displayIt(calcStr, histStr);
}

function compute(data) {
//NUMBERS
if (calcStr === "" && data === 0) {
return 0;
}

if (data >= 0 && data <= 9) {
if (visible) {
calcStr = "";
histStr = ""
total = "";
visible = false;
}

oper_active = true;
calcIt(data, data);
}

//DECIMAL
if (data == "decimal") {
if (dpoint_active === false) {
return 0;
}
if (visible || calcStr == 0 || histStr == 0) {
calcStr = "0.";
histStr = "0.";
total = "0.";
visible = false;
displayIt(calcStr, histStr);
dpoint_active = false;
} else {
calcIt(".", ".");
dpoint_active = false;
}
}

//OPERATORS
if (data == "add") {
if (total == "") {
return 0;
}
if (oper_active == false) {
deleteOne();
}
visible = false;
dpoint_active = true;
calcIt("+", "+");
oper_active = false;
}
if (data == "subtract") {
if (total == "") {
return 0;
}
if (oper_active == false) {
deleteOne();
}
visible = false;
dpoint_active = true;
calcIt("-", "-");
oper_active = false;
}
if (data == "multiply") {
if (total == "") {
return 0;
}
if (oper_active == false) {
deleteOne();
}
visible = false;
dpoint_active = true;
oper_active = false;
calcIt("x", "*");
}
if (data == "divide") {
if (total == "") {
return 0;
}
if (oper_active == false) {
deleteOne();
}
visible = false;
dpoint_active = true;
oper_active = false;
calcIt("/", "/");
}

//EQUALS
if (data == "equals") {
if (total == "" || visible) {
return 0;

index.html // CALCULATOR

<!DOCTYPE html>
<html>

<head>
<title>Javascript Calculator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>

<div class="container-fluid">
<div id="calculator">
<div id="header">
<h1 class="text-center">JS Calculator</h1>
</div>
<div id="display">
0
</div>
<div id="history">
0
</div>
<div id="keypad">
<div class="row text-center">
<div type="button" id="clear" class="btn key col-sm-3">C</div>
<div type="button" id="inv" class="btn key col-sm-3"></div>
<div type="button" id="percent" class="btn key col-sm-3"></div>
<div type="button" id="divide" class="btn key col-sm-3">&divide;</div>
</div>
<div class="row text-center">
<div type="button" id="seven" class="btn key col-sm-3">7</div>
<div type="button" id="eight" class="btn key col-sm-3">8</div>
<div type="button" id="nine" class="btn key col-sm-3">9</div>
<div type="button" id="multiply" class="btn key col-sm-3">&times;</div>
</div>
<div class="row text-center">
<div type="button" id="four" class="btn key col-sm-3">4</div>
<div type = "button" id="five" class="btn key col-sm-3">5</div>
<div type="button" id="six" class="btn key col-sm-3">6</div>
<div type="button" id="subtract" class="btn key col-sm-3">&minus;</div>
</div>
<div class="row text-center">
<div type="button" id="one" class="btn key col-sm-3">1</div>
<div type="button" id="two" class="btn key col-sm-3">2</div>
<div type="button" id="three" class="btn key col-sm-3">3</div>
<div type="button" id="add" class="btn key col-sm-3">+</div>
</div>
<div class="row text-center">
<div type="button" id="decimal" class="btn key col-sm-3">.</div>
<div type="button" id="zero" class="btn key col-sm-3">0</div>
<div type="button" id="delete" class="btn key col-sm-3">del</div>
<div type="button" id="equals" class="btn key col-sm-3">=</div>
</div>
</div>
<footer class="text-center">
  
</footer>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="script.js"></script>
</body>

</html>


Related Solutions

Calculator in JavaScript Project Standards: Students will use click events to capture user input. Students will...
Calculator in JavaScript Project Standards: Students will use click events to capture user input. Students will use variables to store information needed by their application and keep track of their program’s state. Students will use conditionals to control project flow. Project Task You will be building a simple calculator in the browser. It should be able to add, subtract, divide, and multiply. Your program should do the following: Display a standard calculator to the user (you have starter files to...
JS Bin / Tax Calculator / using HTML | CSS | JavaScript ------------------------------------------------------------------------------------------- How can I...
JS Bin / Tax Calculator / using HTML | CSS | JavaScript ------------------------------------------------------------------------------------------- How can I edit the JavaScript below so that when the calculate button is clicked the total price only shows two decimal places by using the toFixed() method? ----------------------------------------------------------------------------------------------------------- JavaScript: // Variables var tax = "tax"; // Tax percentage var taxRate = document.getElementById('tax'); // Selecting tax element // On the time of loading the DOM we are setting the tax rate window.addEventListener('DOMContentLoaded', (event) => { taxRate.value =...
Use external CSS and Javascript files. Use the HTML5 elements to layout the page. In a...
Use external CSS and Javascript files. Use the HTML5 elements to layout the page. In a sidebar include an advertisement that changes its image every three seconds. The can be created in paint and be very simple or more detailed.
Use external CSS and Javascript files Use the HTML5 elements to layout the page. Have a...
Use external CSS and Javascript files Use the HTML5 elements to layout the page. Have a bulleted list and 3 paragraphs this can be loren ipsum. Have the information text fade in when the page is done loading. Stagger the animations so that the text that is higher up on the page fades in before. Add three more animations in addition to the ones above including an interval timer based animation, an event based animation click or hover, and an...
Build a html form (making use of CSS and Javascript) with the following elements. The form...
Build a html form (making use of CSS and Javascript) with the following elements. The form must have validations and within a table format. • Name: a text box where the content must start with 1 upper case characters and no special character (i.e. !, @, #, $, %, &, *). Number is not allowed. The text box must not be empty. • Module code: a text box where the content must start with 3 lower case alphabets and follows...
suggests on how to save the web portfolio Programming languages Chosen: HTML, CSS, and JavaScript. Project...
suggests on how to save the web portfolio Programming languages Chosen: HTML, CSS, and JavaScript. Project Name: Auto Portfolio Project Goal: Create a website that will generate a web portfolio using information inputted by the user. Product Backlog using user stories: As a user, I want to be able to save my web portfolio in a format which I can save so I can use the website later for my own needs. Example: http://www-personal.umich.edu/~hamatilo/
suggests on how to save the web portfolio Programming languages Chosen: HTML, CSS, and JavaScript. Project...
suggests on how to save the web portfolio Programming languages Chosen: HTML, CSS, and JavaScript. Project Name: Auto Portfolio Project Goal: Create a website that will generate a web portfolio using information inputted by the user. Product Backlog using user stories: As a user, I want to be able to save my web portfolio in a format which I can save so I can use the website later for my own needs.
Develop a personal web page for yourself using HTML, CSS, and Javascript Use the following HTML...
Develop a personal web page for yourself using HTML, CSS, and Javascript Use the following HTML tags to design your webpage: <h1>...</h1>,<h3>...</h3>, <h6>...</h6>, <p>...</p>, <b>...</b>, <i>...</i>, <a>...</a>, <img...>, <table>... </table>, <div>...</div>, <form>...</form>, <input type="text">, and <input type= "submit"> Use an external css to change the default style of your webpage. You must use at least one element selector, one id selector, and one class selector Using text input and submit button, allow the user to change the background color of...
Project 2c (Javascript/HTML/CSS)– Mouse Chase: Create a page with a nice, shiny, pretty button on it....
Project 2c (Javascript/HTML/CSS)– Mouse Chase: Create a page with a nice, shiny, pretty button on it. The button should say ‘Click to receive $10!’ However, any time the user’s mouse cursor gets over the button, the button should move to a random location on the page, making the button essentially impossible to click! However, if they do somehow manage to click the button, redirect the user to an image of a 10 trillion Zimbabwe Dollar. Finally, the background color of...
Use a switch statement on a char variable to write a function that's a simple calculator...
Use a switch statement on a char variable to write a function that's a simple calculator that keeps running waiting for input Should have a do while loop that continually loops the function, prompting for a new input and new operator, until the calculator returns 0, in which case it will close.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT