123

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <!-- === BODY CONTENT ===-->
<body>
  <div class="calc_container">
    <div class="skin">
      <span class="brand">NumCrunch</span>
      <div class="display">
        <div class="nav_menu">
          <ul class="menu">
            <li class="menu_item">Edit</li>
            <li class="menu_item">View</li>
            <li class="menu_item">Setting</li>
            <li class="menu_item">Help</li>
          </ul>
        </div>
        <div class="output"></div>
        <div class="error_msg">Invalid entry</div>
        <div class="input">
          <input type="text" class="entry" autofocus="true" contentEditable="true">
        </div>
      </div>
      <div class="panel">
        <button class="panel_btn btn_keys">KEYS</button> 
        <button class="panel_btn btn_lf">
          <i class="fa fa-long-arrow-left"></i>
        </button>
        <button class="panel_btn btn_rt">
          <i class="fa fa-long-arrow-right"></i>
        </button>
        <button class="panel_btn btn_clr">CLEAR</button>
      </div>
    </div> <!-- SKIN -->

    <div class="keypad_container">
      <div class="key_skin">
          <div class="slide_bar">
              <button class="slide_btn" value="1">x<sup>2</sup></button>
              <button class="slide_btn" value="2">^</button>
              <button class="slide_btn" value="3">(</button>
              <button class="slide_btn" value="4">)</button>
              <button class="slide_btn" value="5">&#60;</button>
              <button class="slide_btn" value="6">&#62;</button>      
              <button class="slide_btn" value="7">&#37;</button>
              <button class="slide_btn" value="8">&#33;</button>
            </div>
            <div class="keys">
              <div class="row1">
                <button class="pad_btn" value="7">7</button>
                <button class="pad_btn" value="8">8</button>
                <button class="pad_btn" value="9">9</button>
                <button class="pad_btn" value="÷">&#247;</button>
              </div>
              <div class="row2">
                  <button class="pad_btn" value="4">4</button>
                  <button class="pad_btn" value="5">5</button>
                  <button class="pad_btn" value="6">6</button>
                  <button class="pad_btn" value="×">&#215;</button>
              </div>
              <div class="row3">
                  <button class="pad_btn" value="1">1</button>
                  <button class="pad_btn" value="2">2</button>
                  <button class="pad_btn" value="3">3</button>
                  <button class="pad_btn" value="-">&#45;</button>
              </div>
              <div class="row4">
                  <button class="pad_btn" value="0">0</button>
                  <button class="pad_btn" value=".">&#46;</button>
                  <button class="equal_btn" value="=">&#61;</button>
                  <button class="pad_btn" value="+">&#43;</button>
              </div>
            </div> <!-- KEYS -->    
      </div>
              </div> <!-- KEYPAD_CONTAINER -->
  </div> <!-- CALC_CONTAINER -->

  <template id="output_template">
    <ul class="output_list">
      <li class="expression"></li>
      <li class="result">
        <span class="equal">= </span>
        <span class="answer"></span>
      </li>
    </ul>
  </template>
</body>
            
          
!
            
              /*========================================
  FONTS
==========================================*/

@import url('https://fonts.googleapis.com/css?family=Nunito|Ubuntu+Condensed');

/* ===== GENERAL STYLES ===== */

/* ===== CALC_CONTAINER STYLES ===== */
.calc_container{
  max-width: 800px;
  margin: auto;
}

/* ===== SKIN STYLES ===== */
.skin{
  position: relative;
  min-width: 320px;
  padding:25px;
  padding-bottom: 50px;
  box-sizing: border-box;
  background: linear-gradient(90deg,#4f4f4f,#d2d2d2 0.2%, #555555 2.1%,#555555 98%, #9f9f9f,#5a5a5a 99.9%);
}

/*  @media screen and (min-width: 580px) {
  .skin {
    background: linear-gradient(90deg,#4f4f4f,#d2d2d2 0.2%, #555555 1.7%,#555555 98.3%, #9f9f9f,#5a5a5a 99.9%);
  }
} */

@media screen and (max-width: 580px) {
   *{
  margin: 0;
  padding: 0;
}
  .skin, .key_skin {
    background: linear-gradient(90deg,#4f4f4f,#d2d2d2 0.2%, #555555 1.7%,#555555 98.3%, #9f9f9f,#5a5a5a 99.9%);
  }
   .calc_container{
     min-height: 100vh;
   }
   .key_skin{
     min-height: 50vh;
   }
   .output{
     min-height: 34vh;
   }
}

.brand{
  font-size: 15px;
  position: absolute;
  width: 100%;
  height: 24px;
  top: calc(0% + 4px);
  left: 0%;
  text-align: center;
  color: #444;
  letter-spacing: 3px;
  text-shadow: 1px 2px 1px #888; 
}

.panel{
  display: flex;
  position: relative;
  justify-content: space-between;
  top: 88%;
  left: 5%;
  width: 90%;
  /* keeps panel fixed when output is resized, centers button wrt/ skin's padding-bottom */
  transform: translateY(25px);
}
.panel_btn{
  margin: auto;
  width: calc(90% / 4);
  height: 25px;
  font-size: 70%;
  font-family: 'Nunito', sans-serif;
  text-align: center;
  background-color: #0080FF;
  color: #dfdfdf;
  border-radius: 4px;
}

i.fa-long-arrow-left, i.fa-long-arrow-right{
  font-size: 18px;
}

/* ===== DISPLAY STYLES ===== */
.display{
  position: relative;
  border: 5px #777777 inset;
}
/* ===== NAV_MENU STYLES ===== */
.nav_menu{
  background-color: #dfdfdf;
  font-family: 'Ubuntu Condensed', sans-serif;
}
/* ===== MENU STYLES ===== */
.menu{
  position: relative;
  height: 40px;
  margin: 0;
  padding: 0;
  list-style: none;
}

.menu_item{
  display: inline-block;
  height: 100%;
  margin-left: 5%;
  position: relative;
  top: calc(25%);
}

/* ===== OUTPUT STYLES ===== */
.output{
  height: 150px;
  overflow: auto;
  white-space: nowrap;
  background-color: #c4ccc9;
  position: relative;
  resize: vertical;
}

/* ===== OUTPUT_TEMPLATE STYLES ===== */
.output_list{
  height: calc(150px / 3);
  width: 100%;
  padding: 0;
  margin: 0;
  border-bottom: 1px yellow dotted;
}
.output_list li{
  width: 100%;
  height: 50%;
  list-style: none;
  text-indent: 10px;
  letter-spacing: 1px;
  padding: 2px 0px;
  box-sizing: border-box;
}
.expression{
  background-color: #C1C0B9;
  background-color: #999999;
  color: #DDDDDD;
}
.result{
  background-color: #777777;
}
.equal{
  color: gold;
}
.answer{
  color: skyblue;
}

/* ===== INPUT STYLES ===== */
.input{
  height: 30px;
  position: relative;
}
.entry{
  border: 1px;
  height: 100%;
  background: #E7E6E1;
  font-size: 16px;
  width: calc(100%);
  text-indent: 10px;
}
.error_msg{
  position: absolute;
  visibility: hidden;
  transform: translateY(-20px);
  height: 20px;
  width: 100%;
  text-align: center;
  background-color: rgba(250, 128, 114,1);
}

/* ===== KEYPAD_CONTAINER STYLES ===== */
.keypad_container{
  display: none;    /*keypad is hidden by default*/
  max-width: 800px;
  margin: auto;
}
.keypad_visible{
  display: block;   /*shows keypad when KEYS button clicked*/
}

/* ===== SKIN STYLES ===== */
.key_skin{
  position: relative;
  min-width: 320px;
  padding:25px;
  padding-bottom: 50px;
  border-radius: 0 0 18px 18px;
  box-sizing: border-box;
  background: linear-gradient(90deg,#4f4f4f,#d2d2d2 0.2%, #aaaaaa 2.1%,#aaaaaa 98%, #9f9f9f,#5a5a5a 99.9%);
}

/* ===== SLIDE_BAR STYLES ===== */
.slide_bar{
  display: flex;
  flex-direction: row;
  overflow-x: scroll;
  background-color: #333;
  border: 4px #bbb solid;
  border-bottom: none;
  box-sizing: border-box;
}
.slide_btn{
  height: 40px;
  min-width: calc(100% / 7);
  margin: auto;
  margin: 4px 1px;
  border-radius: 4px;
  font-size: 24px;
  color: honeydew;
  background-color: lightsalmon;  
}
.slide_btn:nth-child(2n){
  background-color: dodgerblue;
}
.slide_btn:nth-child(3n){
  background-color: mediumslateblue;
}
.slide_btn:nth-child(4n){
  background-color: mediumspringgreen;
}
.slide_btn:nth-child(5n){
  background-color: gold:
}
/* ===== KEYS STYLES ===== */
.key{
  padding: 25px;
  max-width: 320px;
  box-sizing: border-box;
}
/* ===== ROW1 STYLES ===== */
.row1, .row2, .row3, .row4{
  display: flex;
  background-color: #cccccc;
  margin: auto;
  border: 4px #bbb solid;
  justify-content: space-between;
}
.pad_btn, .equal_btn{
  height: 80px;
  width: calc(100% / 6);
  margin: auto;
  margin-top: 8px;
  margin-bottom: 8px;
  border-radius: 6px;
  font-size: 24px;
  color: honeydew;
  background: linear-gradient(180deg, #888, #333 12%, #333 88%, #888);
}

.btn_pressed{
  padding-left: 9px;
  padding-right: 7px;
  border-style: inset;
}
            
          
!
            
              /*
CALCULATOR FEATURES:
-This calculator can compute addition, subtraction, multiplication and division.
 Currently, it cannot do any other math operations despite having other operators on the keypad.
-The keypad is accessed by pressing the KEYS button.
-The CLEAR button deletes a single character in the input field when clicked once.
 When the CLEAR button is held for over 1 second it clears all items in the output field.
-When an expression or answer is clicked in the output field it is appended to the input field.
*/

// ========== HTML Reference Variables ==========
const entry = document.querySelector('.entry');
const output = document.querySelector('.output');
const error_msg = document.querySelector('.error_msg');
const btn_lf = document.querySelector('.btn_lf');
const btn_rt = document.querySelector('.btn_rt');
const btn_clr = document.querySelector('.btn_clr');
const btn_keys = document.querySelector('.btn_keys');
const pad_btns = document.querySelectorAll('.pad_btn');
const equal_btn = document.querySelector('.equal_btn');
const keypad_container = document.querySelector('.keypad_container');
// const skin = document.querySelector('.skin');
const key_skin = document.querySelector('.key_skin');

// ========== Template Variables ==========
const doc_fragment = document.createDocumentFragment();
const output_template = document.querySelector('#output_template');
const output_list = output_template.content.querySelector('.output_list');
const expression = output_template.content.querySelector('.expression');
const answer = output_template.content.querySelector('.answer');

// ========== Calculation Variables ==========
let num_arr = [];
let op_arr = [];
let click_time = 0;

// ========== Keyboard Accessibility Functions ==========
entry.addEventListener('keydown', check_entry); // eof()

// ========== Virtual Keypad Accessibility Functions ==========
btn_lf.onmousedown = move_left;
btn_lf.onmouseup = btn_released;
btn_rt.onmousedown = move_right;
btn_rt.onmouseup = btn_released;
btn_clr.onmousedown = start_click_timer;
btn_clr.onmouseup = clear_text;
btn_keys.onmousedown = display_keypad;
btn_keys.onmouseup = btn_released;
equal_btn.onmousedown = equal_btn_pressed;
equal_btn.onmouseup = btn_released;
// skin.onmousedown = keep_input_focused;
key_skin.onmousedown = keep_input_focused;

pad_btns.forEach((btn) => {
  btn.onmousedown = pad_btn_pressed;
  btn.onmouseup = btn_released;
});

// ========== Event Listener Functions ==========
function check_entry(evt) {
  if (evt.key === 'Enter' || this == equal_btn) {
    if (entry.value.match(/(\S)/g) === null) {
      return; // value is empty string, do nothing
    } 
    num_arr = entry.value.match(/(\d|\.\d)+/g); // check if null
    op_arr = entry.value.match(/[\+\-\/\*×÷](?=\s+\d+|\d+|)+/g);
    if (validate_entry()) {
      calculate_entry();
      // clear entry
      entry.value = '';
    }
  }
} // eof()

function keep_input_focused(evt) {
  evt.preventDefault();
  // evt.stopPropagation();
  if (document.activeElement != entry) {
    entry.focus();
  }
} // eof()

function clicked_expression() {
  entry.value += ` ${this.textContent}`;
  entry.focus();
} // eof()

function clicked_result() {
  entry.value += ` ${this.querySelector('.answer').textContent}`;
  entry.focus();
} // eof()

function move_left(evt) {
  evt.preventDefault();
  this.classList.add('btn_pressed'); // simulate button pressed
  // set cursor/caret offset to left by 1
  if (entry.selectionStart > 0) {
    entry.setSelectionRange(entry.selectionEnd - 1, entry.selectionEnd - 1);
  }
} // eof()

function move_right(evt) {
  evt.preventDefault();
  this.classList.add('btn_pressed'); // simulate button pressed
  // set cursor/caret offset to right by 1
  entry.setSelectionRange(entry.selectionEnd + 1, entry.selectionEnd + 1);
} // eof()

function start_click_timer(evt) {
  evt.preventDefault();
  this.classList.add('btn_pressed'); // simulate button pressed
  // get time of the instant mouse button pressed down
  click_time = Date.now();
} // eof()

function clear_text(evt) {
  evt.preventDefault();
  this.classList.remove('btn_pressed'); // simulate button released
  // if clear button is held down for less than 1.2s, delete a char in input
  if (Date.now() - click_time < 1200) {
    // removes the character that precedes current cursor/caret position
    if (entry.selectionStart > 0) {
      entry.setRangeText('', entry.selectionStart - 1, entry.selectionStart);
    }
  } else {
    // else, clear output field
    clear_output();
  }
} // eof()

function display_keypad(evt) {
  evt.preventDefault();
  this.classList.add('btn_pressed'); // simulate button pressed
  keypad_container.classList.toggle('keypad_visible');
} // eof()

// ========== Non-Listener Display Functions ==========
function clear_output() {
  // clear all text in output field
  output.textContent = '';
} // eof()

// ========== Calculator Functions ==========
function calculate_entry() {
  let op_index_1 = op_arr.findIndex(op => op === '/' || op === '÷' || op === '*' || op === '×');

  // check for mult or div
  while (op_index_1 !== -1) {
    eval_operation(op_index_1);
    op_index_1 = op_arr.findIndex(op => op === '/' || op === '÷' || op === '*' || op === '×');
  }

  // check for add or sub
  op_index_1 = op_arr.findIndex(op => op === '+' || op === '-');
  while (op_index_1 !== -1) {
    eval_operation(op_index_1);
    op_index_1 = op_arr.findIndex(op => op === '+' || op === '-');
  }

  // Set precision of result
  num_arr[0] = precisionRound(num_arr[0], 7);
  console.log(num_arr);

  // Append result to display field
  expression.textContent = entry.value;
  answer.textContent = `${num_arr[0]}`;
  doc_fragment.appendChild(document.importNode(output_list, true));
  doc_fragment.querySelector('.expression').onclick = clicked_expression;
  doc_fragment.querySelector('.result').onclick = clicked_result;
  output.appendChild(doc_fragment);
  // scroll to bottom of output div/container
  output.scrollTop = output.scrollHeight;
} // eof()

function eval_operation(op_index) {
  let op_result = 0;
  // compute operation using numbers to right and left of operator
  switch (op_arr[op_index]) {
    case '*':
    case '×':
      op_result = parseFloat(num_arr[op_index]) * parseFloat(num_arr[op_index + 1]);
      break;
    case '/':
    case '÷':
      op_result = parseFloat(num_arr[op_index]) / parseFloat(num_arr[op_index + 1]);
      break;
    case '+':
      op_result = parseFloat(num_arr[op_index]) + parseFloat(num_arr[op_index + 1]);
      break;
    case '-':
      op_result = parseFloat(num_arr[op_index]) - parseFloat(num_arr[op_index + 1]);
      break;
    default:
      throw Error('No operator present in switch statement.');
  }

  // assign result to array, remove used operator and number from arrays
  num_arr[op_index] = op_result;
  num_arr.splice(op_index + 1, 1);
  op_arr.splice(op_index, 1);
} // eof()

function validate_entry() {
  // check for non-operator or digits
  if (entry.value.match(/[^0-9×÷\+\-\*\/\.\s]+/g)) {
    return invalid_entry();
  }
  // check for invalid decimals
  if (entry.value.match(/(\.+\d+\.+|\.(?!\d))+/g)) {
    return invalid_entry();
  }
  // check for invalid whitespace
  if (entry.value.match(/(\d+\s+\d+)/g)) {
    return invalid_entry();
  }
  // check for single number and no operators
  if (num_arr !== null && num_arr.length === 1 && op_arr === null) {
    op_arr = []; // set op_arr to empty array instead of null
    error_msg.style.visibility = 'hidden';
    return true;
  }
  // check for no number or no operator entry
  if (num_arr === null || op_arr === null) {
    return invalid_entry();
  }
  // check for open operations or unary operations
  if (num_arr.length <= op_arr.length) {
    return invalid_entry();
  }
  // entry is valid
  error_msg.style.visibility = 'hidden';
  return true;

  function invalid_entry() {
    console.log('Invalid entry!');
    error_msg.style.visibility = 'visible';
    num_arr = [];
    op_arr = [];
    return false;
  }
} // eof()

// From MDN's Math.round notes.
function precisionRound(number, precision) {
  // var factor = Math.pow(10, precision);
  const factor = 10 ** precision;
  return Math.round(number * factor) / factor;
} // eof()

// ========== Keypad Functions ==========
function pad_btn_pressed(evt) {
  evt.preventDefault();
  this.classList.add('btn_pressed'); // simulate button pressed
  if (document.activeElement == entry) {
    // add char at location of cursor/caret
    entry.setRangeText(this.value, entry.selectionStart, entry.selectionStart);
    // move cursor/caret in front of char added
    entry.setSelectionRange(entry.selectionEnd + 1, entry.selectionEnd + 1);
  }
} // eof()

function btn_released(evt) {
  evt.preventDefault();
  this.classList.remove('btn_pressed'); // simulate button release
} // eof()

function equal_btn_pressed(evt) {
  evt.preventDefault();
  this.classList.add('btn_pressed'); // simulate button pressed
  if (document.activeElement == entry) {
    if (entry.value.match(/(\S)/g) === null) {
      return; // value is empty string, do nothing
    }
    num_arr = entry.value.match(/(\d|\.\d)+/g); // check if null
    op_arr = entry.value.match(/[×÷\+\-\/\*](?=\s+\d+|\d+|)+/g);
    if (validate_entry()) {
      calculate_entry();
      // clear entry
      entry.value = '';
    }
  }
} // eof()
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console