Category: Projects

  • Calculator

    Why? Practice event handling, math operations, and DOM updates.

    <!DOCTYPE html>
    <html>
    <head>
      <title>Calculator</title>
      <style>
    
    input { width: 200px; padding: 10px; margin: 5px; }
    button { padding: 10px; margin: 2px; }
    </style> </head> <body> <h2>Simple Calculator</h2> <input type="text" id="display" disabled> <br> <button onclick="press('1')">1</button> <button onclick="press('2')">2</button> <button onclick="press('3')">3</button> <button onclick="press('+')">+</button> <br> <button onclick="press('4')">4</button> <button onclick="press('5')">5</button> <button onclick="press('6')">6</button> <button onclick="press('-')">-</button> <br> <button onclick="press('7')">7</button> <button onclick="press('8')">8</button> <button onclick="press('9')">9</button> <button onclick="press('*')">*</button> <br> <button onclick="press('0')">0</button> <button onclick="press('/')">/</button> <button onclick="calculate()">=</button> <button onclick="clearDisplay()">C</button> <script>
    function press(value) {
      document.getElementById("display").value += value;
    }
    function calculate() {
      let exp = document.getElementById("display").value;
      document.getElementById("display").value = eval(exp);
    }
    function clearDisplay() {
      document.getElementById("display").value = "";
    }
    </script> </body> </html>

    Explanation:

    • Buttons call press() to append numbers/operators.
    • calculate() uses eval() to evaluate expression.
    • clearDisplay() clears input.
  • Digital Clock

    Why? Learn Date() object and updating UI with setInterval().

    <!DOCTYPE html>
    <html>
    <head>
      <title>Digital Clock</title>
    </head>
    <body>
      <h2 id="clock"></h2>
    
      <script>
    
    function showTime() {
      let time = new Date();
      let hours = time.getHours();
      let minutes = time.getMinutes();
      let seconds = time.getSeconds();
      // Format with leading zeros
      hours = (hours &lt; 10 ? "0" : "") + hours;
      minutes = (minutes &lt; 10 ? "0" : "") + minutes;
      seconds = (seconds &lt; 10 ? "0" : "") + seconds;
      document.getElementById("clock").innerText = ${hours}:${minutes}:${seconds};
    }
    setInterval(showTime, 1000); // update every second
    showTime(); // call immediately
    </script> </body> </html>

    Explanation:

    • new Date() → gets current time.
    • setInterval() updates the time every second.
    • Updates <h2> text with formatted time.