How to create a simple calculator program with javascript

This is a tutorial about how to create a simple calculator program with javascript, css, and html.

First create index.html file

<html>
<head>
    <title>Dice Simulator 2015</title>
    <link rel="stylesheet" href="style.css">
</head>  
<body>
  <h1>Calculator Example</h1>
  <p>Open the JavaScript developer console to interact.</p>
  <script src="calculator.js"></script>

</body>
</html>


Then create style.css file

* {
  font-family: Helvetica, Arial, sans-serif;
  text-align: center;
}


create calculator.js file

var calculator = {
  sum: 0,
  add: function(value) {
    this.sum += value;
  },
  subtract: function(value) {
  this.sum = this.sum - value;
  },
  multiply: function(value) {
  this.sum = this.sum * value;
  },
  divide: function(value) {
  this.sum = this.sum / value;
  },
  clear: function() {
    this.sum = 0;
  }, 
  equals: function() {
    return this.sum;
  }
}


After open javascript console
Type in commands example
calculator.add(1)
calculator.add(1)
calculator.equals() // 3

Create a Dice with HTML, CSS, and Javascript

We are going to create a html, css, and javascript die with this code. For every block of code create the coodinating file extension be it .js .html .css and etc. It should work. Happy coding.

First create index.html


<html>
<head>
    <title>Dice Simulator 2015</title>
    <link rel="stylesheet" href="style.css">
</head>  
<body>
  <p id="placeholder">
  
  </p>
  <button id="button">Roll Dice</button>
  <script src="dice.js"></script>
  <script src="ui.js"></script>
</body>
</html>

Second we are going to create style.css

* {
  font-family: Helvetica, Arial, sans-serif;
  text-align: center;
}
button {
  background-color: rgb(82, 186, 179);
  border-radius: 6px;
  border: none;
  color: rgb(255, 255, 255);
  padding: 10px;
  text-transform: uppercase;
  width: 200px;
  cursor: pointer;
}
#placeholder {
  height: 100px;
  width: 100px;
  padding: 50px;
  margin: 50px auto;
  border: 1px solid gray;
  border-radius: 10px;  
  font-size:80px;
}

3rd we are going to create the ui.js

function printNumber(number) {
  var placeholder = document.getElementById("placeholder");
  placeholder.innerHTML = number;
}

var button = document.getElementById("button");

button.onclick = function() {
  var result = dice.roll();
  printNumber(result);
};

Finally create the object lateral of the javascript file dice.js

var dice = {
sides: 6,
roll: function () {
  var sides = 6;
  var randomNumber = Math.floor(Math.random() * this.sides) + 1;
  return (randomNumber);
}
}

refactored for dice.js using prototype

function Dice(sides) {
  this.sides = sides;
}
Dice.prototype.roll = function diceRoll () {
  var randomNumber = Math.floor(Math.random() * this.sides) + 1;
    return randomNumber;
  }
var dice = new Dice(6);

In conclusion, I hope you learned something from my source code.