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

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...
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.
2. HTML/CSS/JavaScript Under 'project’ create a subdirectory titled ‘travelsite’. Create a slide show for a travel...
2. HTML/CSS/JavaScript Under 'project’ create a subdirectory titled ‘travelsite’. Create a slide show for a travel and tourism company. Use between 8 and 12 pictures that will automatically change every 1 to 3 seconds. You may use the pictures from Assignment 1 and add more to the collection. The slide show will have the following features: Use a background image. The pictures must use a type of ‘transition’ ie Fade in/Fade out when the pictures change. Each picture must include...
Use HTML&CSS& JavaScript to: 3-4) Write a JQuery Ajax program which can communicate with flicker to...
Use HTML&CSS& JavaScript to: 3-4) Write a JQuery Ajax program which can communicate with flicker to get the last pictures taken from any place or related to any concept(s) the user has written in a textbox, say Sydney, train. Some information associated with the image like its topic, time taken, and its link needs to be appeared with it. 3-5) Develop a server which can serve the file you developed in 3-4. 3-6) Add a plugin to the real jQuery...
Create a web calculator with JavaScript. Only four operations (Add, Sub, Multiplication, and Division) Use a...
Create a web calculator with JavaScript. Only four operations (Add, Sub, Multiplication, and Division) Use a CE button to cancel the operation.    Use the following website or any online resource as a reference. Don’t use their CSS or any other code.                 https://freshman.tech/calculator/ I am trying to learn please make comments then I will understand better.
Java Language Only Use Java FX In this project we will build a BMI calculator. BMI...
Java Language Only Use Java FX In this project we will build a BMI calculator. BMI is calculated using the following formulas: Measurement Units Formula and Calculation Kilograms and meters (or centimetres) Formula: weight (kg) / [height (m)]2 The formula for BMI is weight in kilograms divided by height in meters squared. If height has been measured in centimetres, divide by 100 to convert this to meters. Pounds and inches Formula: 703 x weight (lbs) / [height (in)]2 When using...
Programming Project #1: Manage Simple Expenses Objectives: • Use basic C++ constructs: if, switch, repetition (looping)...
Programming Project #1: Manage Simple Expenses Objectives: • Use basic C++ constructs: if, switch, repetition (looping) and functions • Perform simple data type and string object manipulations • Solve problem, design solution and implement using C++ Description: Write a menu-driven program named “ManageSimpleExpenses” that provides the following options: 1. Earn 2. Spend 3. Show logs 4. Exit Basically, the program allows the user to enter earning or spending amounts and keep track of the current balance. It also print out...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT