Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <section>
  <div class="calculator"></div>
</section>
              
            
!

CSS

              
                
*,
*::before,
*::after {
  box-sizing: border-box;
}

html {
  font-family: sans-serif;
  line-height: 1.15;
  -webkit-text-size-adjust: 100%;
  -ms-text-size-adjust: 100%;
  -ms-overflow-style: scrollbar;
  -webkit-tap-highlight-color: transparent;
  font-size: 62.5%;
  height: 100%;
}

@-ms-viewport {
  width: device-width;
}

article, aside, dialog, figcaption, figure, footer, header, hgroup, main, nav, section {
  display: block;
}

body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  font-size: 1.4rem;
  font-weight: normal;
  line-height: 1.5;
  color: #212529;
  text-align: left;
  background-color: #2f98e4;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  overflow: auto;
}
section {
  display: flex;
  flex: 1;
  box-sizing: border-box;
  overflow: auto;
  align-items: center;
  justify-content: center;
  padding: 1rem;
  min-height: 540px;
}

.calculator {
  width: 320px;
  height: 480px;
  display: inline-flex;
  flex-direction: column;
  box-shadow: 0px 10px 20px 0px rgba(0,0,0,0.5);
}

.calculator-display {
  color: white;
  background: #1c191c;
  line-height: 130px;
  font-size: 6em;
  position: relative;
  padding: 0 10px;
}

.auto-scaling-text {
  display: inline-block;
  padding: 0 30px;
  position: absolute;
  right: 0;
  transform-origin: right;
}

button {
  display: block;
  background: none;
  border: none;
  padding: 0;
  font-family: inherit;
  user-select: none;
  cursor: pointer;
  outline: none;

  -webkit-tap-highlight-color: rgba(0,0,0,0);
}

button:active {
  box-shadow: inset 0px 0px 80px 0px rgba(0,0,0,0.25);
}
.calculator-key {
  width: 80px;
  height: 70px;
  border-top: 1px solid #777;
  border-right: 1px solid #666;
  text-align: center;
  line-height: 70px;
}

.calculator .input-keys {
  width: 240px;
}

.calculator .function-keys {
  display: flex;
}

.calculator .digit-keys {
  background: #e0e0e7;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.calculator-keypad {
  height: 350px;
  display: flex;
}

.calculator .function-keys .calculator-key {
  font-size: 2em;
}

.calculator .function-keys .key-multiply {
  line-height: 50px;
}

.calculator .digit-keys .calculator-key {
  font-size: 2.25em;
}

.calculator .digit-keys .key-0 {
  width: 160px;
  text-align: left;
  padding-left: 32px;
}

.calculator .digit-keys .key-dot {
  padding-top: 1em;
  font-size: 0.75em;
}

.calculator .operator-keys .calculator-key {
  color: white;
  border-right: 0;
  font-size: 3em;
}

.calculator .function-keys {
  background: linear-gradient(to bottom, rgba(202,202,204,1) 0%, rgba(196,194,204,1) 100%);
}

.calculator .operator-keys {
  background:  linear-gradient(to bottom, rgba(252,156,23,1) 0%, rgba(247,126,27,1) 100%);
}

@media only screen and (max-width: 414px) {
  .calculator {
    transform: scale(.80)
  }
}
              
            
!

JS

              
                /** @jsx h */
const { h, render} = composi
const { DataStore } = datastore


const DigitKeys = [7, 8, 9, 4, 5, 6, 1, 2, 3, 0]

const CalculatorOperations = [
  {
    key: '/',
    name: 'divide',
    symbol: '÷',
    func: (prevValue, nextValue) => prevValue / nextValue
  },
  {
    key: '*',
    name: 'multiply',
    symbol: '×',
    func: (prevValue, nextValue) => prevValue * nextValue
  },
  {
    key: '-',
    name: 'subtract',
    symbol: '−',
    func: (prevValue, nextValue) => prevValue - nextValue
  },
  {
    key: '+',
    name: 'add',
    symbol: '+',
    func: (prevValue, nextValue) => prevValue + nextValue
  },
  {
    key: '=',
    name: 'equals',
    symbol: '=',
    func: (prevValue, nextValue) => nextValue
  }
]

const getFormattedValue = value => {
  const language = navigator.language || 'en-US'

  let formattedValue = parseFloat(value).toLocaleString(language, {
    useGrouping: true,
    maximumFractionDigits: 6
  })

  const match = value.match(/\.\d*?(0*)$/)

  if (match) { formattedValue += (/[1-9]/).test(match[0]) ? match[1] : match[0] }

  return formattedValue.length >= 14 ? String(parseFloat(value).toExponential()) : formattedValue
}

function CalculatorKey({ onClick, className, keyValue }) {
  return (
    <button onclick={onClick} class={`calculator-key ${className}`}>{keyValue}</button>
  )
}

function CalculatorDisplay({ value }) {
  return (
    <div class="calculator-display">
      {getFormattedValue(value)}
    </div>
  )
}

const dataStore = new DataStore({
    value: null,
    displayValue: '0',
    operator: null,
    scale: 1,
    waitingForOperand: false
  })
window.dataStore = dataStore

dataStore.watch('update-display', data => {
  render(<Calculator data={dataStore.state} />, '.calculator')
})

function Calculator({ data }) {
  const { displayValue } = dataStore.state
  const CLEARDISPLAY = displayValue !== '0'
  const clearText = CLEARDISPLAY ? 'C' : 'AC'

  const init = el => {
    el.addEventListener('keydown', handleKeyDown)
  }
  const clearAll = () => {
    dataStore.setState({
      value: null,
      displayValue: '0',
      operator: null,
      waitingForOperand: false
    })
  }
  const clearDisplay = () => {
    dataStore.setState({
      displayValue: '0'
    })
  }
  const clearLastChar = () => {
    const { displayValue } = dataStore.state

    dataStore.setState({
      displayValue: displayValue.substring(0, displayValue.length - 1) || '0'
    })
  }
  const toggleSign = () => {
    const { displayValue } = dataStore.state
    const newValue = parseFloat(displayValue) * -1

    dataStore.setState({
      displayValue: String(newValue)
    })
  }
  const inputPercent = () => {
    const { displayValue } = dataStore.state
    const currentValue = parseFloat(displayValue)

    if (currentValue === 0) { return }

    const fixedDigits = displayValue.replace(/^-?\d*\.?/, '')
    const newValue = parseFloat(displayValue) / 100

    dataStore.setState({
      displayValue: String(newValue.toFixed(fixedDigits.length + 2))
    })
  }
  const performOperation = nextOperator => {
    const { value, displayValue, operator } = dataStore.state
    const inputValue = parseFloat(displayValue)

    if (value == null) {
      dataStore.setState({
        value: inputValue
      })
    } else if (operator) {
      const currentValue = value || 0
      const operation = CalculatorOperations.find(item => operator == item.key)
      const newValue = operation.func(currentValue, inputValue)

      dataStore.setState({
        value: newValue,
        displayValue: String(newValue)
      })
    }

    dataStore.setState(prevState => {
      prevState.waitingForOperand = true
      prevState.operator = nextOperator
      return prevState
    })
  }
  const inputDigit = digit => {
    const { displayValue, waitingForOperand } = dataStore.state

    if (waitingForOperand) {
      dataStore.setState(prevState => {
        prevState.displayValue = String(digit)
        prevState.waitingForOperand = false
        return prevState
      })
    } else {
      dataStore.setState(prevState => {
        prevState.displayValue = displayValue === '0' ? String(digit) : displayValue + digit
        return prevState
      })
    }
  }
  const inputDot = () => {
    const { displayValue, waitingForOperand } = dataStore.state
    if (waitingForOperand) {
      dataStore.setState({
        displayValue: '0.',
        waitingForOperand: false
      })
    } else if (!(/\./).test(displayValue)) {
      dataStore.setState(prevState => {
        prevState.displayValue = displayValue + '.'
        prevState.waitingForOperand = false
        return prevState
      })
    }
  }
  const handleKeyDown = event => {
    let { key } = event

    if (key === 'Enter') { key = '=' }

    if ((/\d/).test(key)) {
      event.preventDefault()
      inputDigit(parseInt(key, 10))
    } else if (key in CalculatorOperations) {
      event.preventDefault()
      performOperation(key)
    } else if (key === '.') {
      event.preventDefault()
      inputDot()
    } else if (key === '%') {
      event.preventDefault()
      inputPercent()
    } else if (key === 'Backspace') {
      event.preventDefault()
      clearLastChar()
    } else if (key === 'Clear') {
      event.preventDefault()

      if (dataStore.state.displayValue !== '0') {
        clearDisplay()
      } else {
        clearAll()
      }
    }
  }
  return (
    <div class="calculator">
      <CalculatorDisplay value={displayValue} />
      <div class="calculator-keypad">
        <div class="input-keys">
          <div class="function-keys">
            <CalculatorKey
              className="key-clear"
              onClick={() => CLEARDISPLAY ? clearDisplay() : clearAll()}
              keyValue={clearText}
            >
            </CalculatorKey>
            <CalculatorKey
              className="key-sign"
              onClick={toggleSign}
              keyValue='±'>
            </CalculatorKey>
            <CalculatorKey
              className="key-percent"
              onClick={inputPercent}
              keyValue='%'
            >
            </CalculatorKey>
          </div>
          <div className="digit-keys">
            {
              DigitKeys.map(el =>
                <CalculatorKey
                  key={`key-${el}`}
                  className={`key-${el}`}
                  onClick={() => inputDigit(el)}
                  keyValue={el}
                >
                </CalculatorKey>
              )
            }
            <CalculatorKey
              className="key-dot"
              onClick={inputDot}
              keyValue='●'
            >
            </CalculatorKey>
          </div>
        </div>
        <div className="operator-keys">
          {
            CalculatorOperations.map(item => (
              <CalculatorKey
                key={item.name}
                className={`key-${item.name}`}
                onClick={() => performOperation(item.key)}
                keyValue={item.symbol}
              >
              </CalculatorKey>
            ))
          }
        </div>
      </div>
    </div>
  )
}

render(<Calculator data={dataStore.state}/>, '.calculator')


              
            
!
999px

Console