JSFiddle - React, Tailwind, and code Playground

by Rolf

HTML

<form id="calcForm">
<input id="rechner" type="text" width="200">
<button type="submit">=</button>
<form>
<output id="message"></output>
<ul id="history">
</ul>

CSS

output { display: block; color:red; }

#history {
  list-style: none;
}

JavaScript

let calc = document.getElementById("rechner");
let go   = document.getElementById("eval");
let msg  = document.getElementById("message");
let history = document.getElementById("history");

calc.focus();
calc.form.addEventListener("submit", function(e) {
   compute();
   e.preventDefault();
});
history.addEventListener("click", function(e) {
   calc.value = e.target.textContent;
   calc.focus();
})

function compute() {
   try {
      let expression = calc.value
      calc.value = eval(expression);

      msg.textContent = "";

			addToHistory(expression);
   }
   catch (e) {
      if (!e.constructor) return;
      let name = e.constructor.name;
      msg.textContent = name;
   }
}

function addToHistory(expr) {
   // duplicate entry?
   let h = document.querySelectorAll("#history button");
   if ([].some.call(h, b => b.textContent == expr))
      return;

   // new entry, add at top
   let hist = document.createElement("li");
   let btn = document.createElement("button");
   hist.appendChild(btn);
   btn.textContent = expr;
   btn.type="button";
   history.insertBefore(hist, history.firstChild);
}