Stack Exchange network consists of 183 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
I'm learning JavascriptJavaScript and as a start I'm trying to create a calculator.
I'm learning Javascript and as a start I'm trying to create a calculator.
I'm learning JavaScript and as a start I'm trying to create a calculator.
Right im learning Javascript and as a start im trying to create javascript calculator.
comments please
window.onload = function() { var numbers = document.getElementsByTagName('span'); var result = document.querySelectorAll('.result')[0]; var clear = document.getElementsByClassName('clear')[0]; for (var i = 0; i < numbers.length; i += 1) { if (numbers[i].innerHTML === '=') { numbers[i].addEventListener("click", calculate(i)); } else { numbers[i].addEventListener("click", addValue(i)); } } clear.onclick = function() { result.innerHTML = ''; }; function addValue(i) { return function() { if (numbers[i].innerHTML === '÷') { result.innerHTML += '/'; } else if (numbers[i].innerHTML === 'x') { result.innerHTML += '*'; } else { result.innerHTML += numbers[i].innerHTML; } }; } function calculate(i) { return function() { result.innerHTML = eval(result.innerHTML); }; } };
* { margin: 0; padding: 0; box-sizing: border-box; font: bold 15px Arial, sans-serif; } #calculator { width: 312px; height: auto; margin: 100px auto; padding: 10px 10px 10px 10px; background: #0088cc; } .top span.clear { float: left; } .top .result { height: 40px; width: 212px; float: left; background: rgba(0, 0, 0, 0.2); border-radius: 3px; font-size: 17px; line-height: 40px; color: white; text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2); text-align: right; letter-spacing: 1px; } .keys, .top { overflow: hidden; } .keys span, .top span.clear { float: left; position: relative; top: 0; cursor: pointer; width: 66px; height: 36px; background: white; border-radius: 3px; margin: 0 7px 11px 0; line-height: 36px; text-align: center; transition: all 0.2s ease; } span.equ { background: #00FF19; } .top span.clear { background: red; color: white; font-size: 17px; } .keys span:active { top: 3px; } .top span.clear:active { top: 3px; }
<div id="calculator"> <div class="top"> <span class="clear">C</span> <div class="result"></div> </div> <div class="keys"> <span>7</span> <span>8</span> <span>9</span> <span>+</span> <span>4</span> <span>5</span> <span>6</span> <span>-</span> <span>1</span> <span>2</span> <span>3</span> <span>÷</span> <span>0</span> <span>.</span> <span class="equ">=</span> <span>x</span> </div> </div>