Calculator

A simple calculator

  1. // ==UserScript==
  2. // @name Calculator
  3. // @namespace -
  4. // @version 2
  5. // @description A simple calculator
  6. // @author discord: twilightmoon_
  7. // @match *://*.yourwebsite.com/*
  8. // @grant none
  9. // ==/UserScript==
  10. (function() {
  11. 'use strict';
  12.  
  13. // Create a container for the calculator
  14. const calculatorContainer = document.createElement('div');
  15. calculatorContainer.id = 'calculator-container';
  16. calculatorContainer.style.position = 'fixed';
  17. calculatorContainer.style.bottom = '10px';
  18. calculatorContainer.style.right = '10px';
  19. calculatorContainer.style.backgroundColor = 'white';
  20. calculatorContainer.style.padding = '10px';
  21. calculatorContainer.style.border = '1px solid #ccc';
  22. calculatorContainer.style.boxShadow = '0 0 5px rgba(0, 0, 0, 0.2)';
  23. calculatorContainer.style.zIndex = '9999';
  24. calculatorContainer.style.cursor = 'move';
  25. calculatorContainer.draggable = true;
  26.  
  27. calculatorContainer.addEventListener('drag', (e) => {
  28. e.preventDefault();
  29. });
  30.  
  31. // Create a display for the calculator
  32. const display = document.createElement('input');
  33. display.type = 'text';
  34. display.style.width = '100%';
  35. display.style.marginBottom = '10px';
  36. display.addEventListener('input', updateInput);
  37. calculatorContainer.appendChild(display);
  38.  
  39. // Create calculator buttons in the order of a real calculator
  40. const buttonLayout = [
  41. ['7', '8', '9', '/'],
  42. ['4', '5', '6', '*'],
  43. ['1', '2', '3', '-'],
  44. ['0', '.', '=', '+'],
  45. ['C']
  46. ];
  47.  
  48. buttonLayout.forEach(row => {
  49. const buttonRow = document.createElement('div');
  50. buttonRow.style.display = 'flex';
  51.  
  52. row.forEach(button => {
  53. const btn = document.createElement('button');
  54. btn.textContent = button;
  55. btn.style.flex = '1';
  56. btn.style.padding = '10px';
  57. btn.style.margin = '2px';
  58. btn.addEventListener('click', () => onButtonClick(button));
  59. buttonRow.appendChild(btn);
  60. });
  61.  
  62. calculatorContainer.appendChild(buttonRow);
  63. });
  64.  
  65. // Add the calculator to the page
  66. document.body.appendChild(calculatorContainer);
  67.  
  68. let currentInput = '';
  69.  
  70. // Function to handle button clicks
  71. function onButtonClick(button) {
  72. if (button === '=') {
  73. try {
  74. display.value = eval(currentInput);
  75. } catch (error) {
  76. display.value = 'Error';
  77. }
  78. currentInput = '';
  79. } else if (button === 'C') {
  80. display.value = '';
  81. currentInput = '';
  82. } else {
  83. currentInput += button;
  84. display.value = currentInput;
  85. }
  86. }
  87.  
  88. // Function to update input from typing
  89. function updateInput() {
  90. currentInput = display.value;
  91. }
  92. })();