css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

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.

            
              <script src='https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js'></script>

<div class="calculator">
  <div id="display">0</div>

  <div class="calculator__keys">
    <button class="operator" data-action="add" id="add">+</button>
    <button class="operator" data-action="subtract" id="subtract">-</button>
    <button class="operator" data-action="multiply" id="multiply">&times;</button>
    <button class="operator" data-action="divide" id="divide">÷</button>
    <button id="seven">7</button>
    <button id="eight">8</button>
    <button id="nine">9</button>
    <button id="four">4</button>
    <button id="five">5</button>
    <button id="six">6</button>
    <button id="one">1</button>
    <button id="two">2</button>
    <button id="three">3</button>
    <button id="zero">0</button>
    <button data-action="decimal" id="decimal">.</button>
    <button data-action="clear" id="clear">AC</button>
    <button data-action="calculate" id="equals">=</button>
  </div>
</div>
            
          
!
            
              * {
  outline: none;
  box-sizing: border-box;
  font-family: monospace;
  font-size: 1.25rem;
}

body {
  background-image: linear-gradient(to bottom, #292E49, #536976, #BBD2C5);
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
.calculator {
  border-radius: 15px;
  box-shadow: 0 0 40px 0px rgba(0, 0, 0, 0.2);
  margin: 0 auto;
  width: 400px;
  overflow: hidden;
}

#display {
  background-color: #222222;
  color: #fff;
  font-size: 1.8em;
  padding: 0.3em 0.75em;
  text-align: right;
}

.calculator__keys {
  background-color: #292E49;
  display: grid;
  grid-gap: 1.2px;
  grid-template-columns: repeat(4, 100px);
  grid-template-rows: repeat(5, 1fr);
}

button {
  background-color: #BBD2C5;
  padding: 0.5em 1.25em;
  position: relative;
  text-align: center;
  border: 0;
  border-radius: 0;
}
button:active {
  color: #536976;
}

.operator {
  background-color: #292E49;
}

#equals {
  background-image: linear-gradient(to bottom, #292E49 5%, #536976 40%, #536976);
  grid-column: -2;
  grid-row: 2 / span 4;
}

            
          
!
            
              // Shoutout to Zell Liew for an awesome
// and very helpful tutorial
// Couldn't have figured this out without his example
// https://zellwk.com/blog/calculator-part-1/?ck_subscriber_id=295723487

const calculator = document.querySelector('.calculator')
const display = calculator.querySelector('#display')
const keys = calculator.querySelector('.calculator__keys')

keys.addEventListener('click', e => {
  if (e.target.matches('button')) {
    const key = e.target
    const action = key.dataset.action
    const keyContent = key.textContent
    const displayedNum = display.textContent
    const previousKeyType = calculator.dataset.previousKeyType

    Array.from(key.parentNode.children)
      .forEach(k => k.classList.remove('is-depressed'))

    if (!action) {
      if (
        displayedNum === '0' ||
        previousKeyType === 'operator' ||
        previousKeyType === 'calculate'
      ) {
        display.textContent = keyContent
      } else {
        display.textContent = displayedNum + keyContent
      }
      calculator.dataset.previousKeyType = 'number'
    }

    if (action === 'decimal') {
      if (!displayedNum.includes('.')) {
        display.textContent = displayedNum + '.'
      } else if (
        previousKeyType === 'operator' ||
        previousKeyType === 'calculate'
      ) {
        display.textContent = '0.'
      }

      calculator.dataset.previousKeyType = 'decimal'
    }

    if (
      action === 'add' ||
      action === 'subtract' ||
      action === 'multiply' ||
      action === 'divide'
    ) {
      const firstValue = calculator.dataset.firstValue
      const operator = calculator.dataset.operator
      const secondValue = displayedNum

      if (
        firstValue &&
        operator &&
        previousKeyType !== 'operator' &&
        previousKeyType !== 'calculate'
      ) {
        const calcValue = calculate(firstValue, operator, secondValue)
        display.textContent = calcValue
        calculator.dataset.firstValue = calcValue
      } else {
        calculator.dataset.firstValue = displayedNum
      }

      key.classList.add('is-depressed')
      calculator.dataset.previousKeyType = 'operator'
      calculator.dataset.operator = action
    }

    if (action === 'clear') {
      if (key.textContent === 'AC') {
        calculator.dataset.firstValue = ''
        calculator.dataset.modValue = ''
        calculator.dataset.operator = ''
        calculator.dataset.previousKeyType = ''
      } else {
        key.textContent = 'AC'
      }

      display.textContent = 0
      calculator.dataset.previousKeyType = 'clear'
    }

    if (action === 'calculate') {
      let firstValue = calculator.dataset.firstValue
      const operator = calculator.dataset.operator
      let secondValue = displayedNum
      
      if (firstValue) {
        if (previousKeyType === 'calculate') {
          firstValue = displayedNum
          secondValue = calculator.dataset.modValue
        }
        
        display.textContent = calculate(firstValue, operator, secondValue)
      }
      
      calculator.dataset.modValue = secondValue;
      calculator.dataset.previousKeyType = 'calculate'
    }
  }
})

const calculate = (left, op, right) => {
  let result = ''
  if (op === 'add') {
    result = parseFloat(left) + parseFloat(right)
  } else if (op === 'subtract') {
    result = parseFloat(left) - parseFloat(right)
  } else if (op === 'multiply') {
    result = parseFloat(left) * parseFloat(right)
  } else if (op === 'divide') {
    result = parseFloat(left) / parseFloat(right)
  }
  return result
}


            
          
!
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.
Loading ..................

Console