Index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple Calculator</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="calculator"> <input type="text" class="display" id="result" readonly> <table> <tr> <td><button onclick="display('7')">7</button></td> <td><button onclick="display('8')">8</button></td> <td><button onclick="display('9')">9</button></td> <td><button onclick="display('/')">/</button></td> </tr> <tr> <td><button onclick="display('4')">4</button></td> <td><button onclick="display('5')">5</button></td> <td><button onclick="display('6')">6</button></td> <td><button onclick="display('*')">*</button></td> </tr> <tr> <td><button onclick="display('1')">1</button></td> <td><button onclick="display('2')">2</button></td> <td><button onclick="display('3')">3</button></td> <td><button onclick="display('-')">-</button></td> </tr> <tr> <td><button onclick="display('0')">0</button></td> <td><button onclick="display('.')">.</button></td> <td><button onclick="clearScreen()">C</button></td> <td><button onclick="calculate()">=</button></td> </tr> </table> </div> <script src="script.js"></script> </body> </html>
This code creates a basic calculator with the following features:
- A display to show the current input and result.
- Buttons for numbers, operators, and clear and calculate functions.
- Clicking a number or operator button adds it to the display.
- Clicking the clear button clears the display.
- Clicking the equals button evaluates the expression in the display and shows the result.
Note: Using the eval
function in JavaScript can be a security risk as it can execute arbitrary code. It's recommended to use safer alternatives for evaluating user expressions in production environments.